I'd like to set UserControl's Property like below. 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. It currently does not know where to fetch 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.
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
. Take a look at the MVVM Pattern documentation to help out.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.