要像下面那样设置用户控件的属性。 我怎样才能做到这一点?
<HierarchicalDataTemplate DataType="{x:Type src:Class}">
<UserControls:ClassBlock classInstance="{Binding PropertyFromClass}"/>
</HierarchicalDataTemplate>
答案 0 :(得分:0)
您需要设置用户控件的DataContext。它目前不知道在哪里获取PropertyFromClass。你可以这样做:
<HierarchicalDataTemplate DataType="{x:Type src:Class}">
<UserControls:ClassBlock classInstance="{Binding PropertyFromClass}">
<UserControls:ClassBlock.DataContext>
<MyViewModels:SomeViewModelHavingPropertyFromClass />
</UserControls:ClassBlock.DataContext>
</UserControls:ClassBlock
</HierarchicalDataTemplate>
如果您的属性是代码隐藏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>
这样可以解决问题,但确实应该在您的View Model
中。请查看MVVM Pattern documentation以获取帮助。