[英]WPF Binding: How to set Binding Source inside UserControl XAML
I'd like to set UserControl's Property like below. 我想像下面那样设置UserControl的Property。 How can I achieve this? 我该如何实现?
<HierarchicalDataTemplate DataType="{x:Type src:Class}">
<UserControls:ClassBlock classInstance="{Binding PropertyFromClass}"/>
</HierarchicalDataTemplate>
You need to set the DataContext of the user control. 您需要设置用户控件的DataContext。 It currently does not know where to fetch PropertyFromClass. 当前它不知道在哪里获取PropertyFromClass。 You can do it like such: 您可以这样做:
<HierarchicalDataTemplate DataType="{x:Type src:Class}">
<UserControls:ClassBlock classInstance="{Binding PropertyFromClass}">
<UserControls:ClassBlock.DataContext>
<MyViewModels:SomeViewModelHavingPropertyFromClass />
</UserControls:ClassBlock.DataContext>
</UserControls:ClassBlock
</HierarchicalDataTemplate>
If your property is a property in your code-behind ClassBlock.Xaml.cs
file, which it sounds like it might be, you must implement the INotifyPropertyChanged
interface on the property. 如果您的属性是ClassBlock.Xaml.cs
文件背后的代码中的一个属性(听起来可能是这样),则必须在该属性上实现INotifyPropertyChanged
接口。
public partial class ClassBlock: UserControl, INotifyPropertyChanged
{
private string classInstance;
public ClassBlock()
{
this.InitializeComponent();
}
public string ClassInstance
{
get
{
return this.classInstance;
}
set
{
this.classInstance= value;
this.OnPropertyChanged();
}
}
public void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
if (this.PropertyChanged != null)
{
// Invoke the event handlers attached by other objects.
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
<HierarchicalDataTemplate DataType="{x:Type src:Class}">
<!-- Upper case ClassInstance -->
<UserControls:ClassBlock ClassInstance="{Binding PropertyFromClass}" />
</HierarchicalDataTemplate>
That would fix the issue, although that really should be in your View Model
. 这将解决问题,尽管那确实应该在您的View Model
。 Take a look at the MVVM Pattern documentation to help out. 查看MVVM Pattern文档以寻求帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.