WPF绑定:如何在UserControl XAML中设置绑定源

时间:2014-05-30 19:09:31

标签: c# wpf xaml

要像下面那样设置用户控件的属性。 我怎样才能做到这一点?

<HierarchicalDataTemplate DataType="{x:Type src:Class}">
      <UserControls:ClassBlock classInstance="{Binding PropertyFromClass}"/>
</HierarchicalDataTemplate>

1 个答案:

答案 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));
        }
    }
}

XAML

<HierarchicalDataTemplate DataType="{x:Type src:Class}">
    <!-- Upper case ClassInstance -->
    <UserControls:ClassBlock ClassInstance="{Binding PropertyFromClass}" />
</HierarchicalDataTemplate>

这样可以解决问题,但确实应该在您的View Model中。请查看MVVM Pattern documentation以获取帮助。