我想通过XAML将自定义对象绑定到usercontrol:
我有一个MainPage和一个用户控件。模型对象:
public class Test
{
public int Id { get; set; }
public string Value { get; set; }
}
MainPage:
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));
}
}
}
和用户控件:
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)));
}
在我的MainPage.xaml中,我通过将dependencyproperty PropertyTest绑定到TestToto来创建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:
第一个TextBox显示来自MainPage和第二个Textbox的Value属性应该显示相同的内容。
有关信息,请关注this post from SO。
提前致谢
此致