を結合して、ユーザーコントロールにカスタムオブジェクトを渡す私は、XAMLを経由してユーザーコントロールにカスタムオブジェクトをバインドしたい:は、XAMLは
私はメインページとユーザーコントロールを持っています。モデルオブジェクト:
public class Test
{
public int Id { get; set; }
public string Value { get; set; }
}
メインページ:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
}
public class MainPageViewModel : INotifyPropertyChanged
{
public MainPageViewModel()
{
TestToto = new Test() { Id = 1, Value = "A value" };
}
public event PropertyChangedEventHandler PropertyChanged;
private Test _test;
public Test TestToto
{
get { return _test; }
set { _test = value; NotifyPropertyChanged("TestToto"); }
}
protected void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
とユーザーコントロール:私のMainPage.xamlをで
public sealed partial class MyUserControl1 : UserControl
{
public MyUserControl1()
{
this.InitializeComponent();
this.DataContext = this;
Debug.WriteLine($"ID =====================> {PropertyTest}");
}
public Test PropertyTest
{
get { return (Test)GetValue(PropertyTestProperty); }
set { SetValue(PropertyTestProperty, value); }
}
// Using a DependencyProperty as the backing store for PropertyTest. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PropertyTestProperty =
DependencyProperty.Register("PropertyTest", typeof(Test), typeof(MyUserControl1), new PropertyMetadata(default(Test)));
}
は、私はTestTotoにしたDependencyProperty PropertyTestを結合することによってMyUserControl1のインスタンスを作成します(MainPage.xaml.cs参照):
<Grid>
<TextBox Grid.Row="1"
Text="{Binding TestToto.Value}" />
<local:MyUserControl1 Grid.Row="2"
PropertyTest="{Binding DataContext.TestToto, ElementName=maPage}" />
</Grid>
ここでmaPageはMainPageページの名前です。その後、私のユーザーコントロールのXAMLで私が持っている:
<Grid>
<TextBox x:Name="textBox"
HorizontalAlignment="Left"
Margin="30,47,0,0"
TextWrapping="Wrap"
Text="{Binding PropertyTest.Value}"
VerticalAlignment="Top"
Width="146" />
</Grid>
問題はPropertyTest DPは常にnullであるということです:メインページ及び第二のテキストボックスから
まずテキストボックス表示Valueプロパティは同じdiplay必要があります。
私は、this post from SOに従っています。事前に
おかげ
よろしく
MainPageViewModelのインスタンスを作成してMainPageのDataContextに割り当てているわけではありませんか? –
Oh ****、thansk you、私に説明させてください:私のメインページのxamlには、MainPageViewModelというインスタンスがありますが、Grid.DataContext> Gridのように設定されています。 DataContext> 私のUserControlでは、DataContextがMainPageスコープにあり(グリッドスコープにはありませんでした)、今すぐ動作します。 –
ArthurCPPCLI