c# - WPF UserControl绑定(bind)问题

标签 c# wpf

我喜欢创建一个拥有自己的 Header 属性的 UserControl。

public partial class SomeClass: UserControl, INotifyPropertyChanged
{
    public SomeClass()
    {
        InitializeComponent();
    }

    private string header;
    public string Header
    {
        get { return header; }
        set 
        { 
            header = value;
            OnPropertyChanged("Header");
        }
    }

    protected void OnPropertyChanged(string propertyName)                    
    {                                                                        
        if (this.PropertyChanged != null)                                    
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

在 UserContol xaml 中:

Label Name="lbHeader" Grid.Column="0" Content="{Binding Path=Header}"

如果我设置值:AA2P.Header = "SomeHeeaderText";label.Caption 将不会改变。我该如何解决这个问题?

在 Windows xaml 中:

uc:SomeClass x:Name="AA2P" 

如果我直接给标签 (lbHeader.Content = header;) 而不是 OnPropertyChanged("Header"); 赋值它的工作但是,为什么它不使用 OnPropertyChanged 吗?


我需要将 DataContext 用于其他用途。我尝试使用依赖属性,但出了点问题。

public partial class tester : UserControl
{
    public tester()
    {
        InitializeComponent();
    }

    public string Header
    {
        get { return (string)GetValue(MyDependencyProperty); }
        set { SetValue(MyDependencyProperty, value); }
    }
    public static readonly DependencyProperty MyDependencyProperty =
    DependencyProperty.Register("MyDependencyProperty", typeof(string), typeof(string));

}


<UserControl ... x:Name="mainControl">
<TextBlock Text="{Binding ElementName=mainControl, Path=MyDependencyProperty}"/>
</UserControl>


<Window ...>
<my:tester Header="SomeText" />
</Window>

它不起作用。我做错了什么? 谢谢!

最佳答案

最简单的方法是仅使用对象的 DataContext。一种方法是直接在构造函数中这样做:

public SomeClass()
    {
        InitializeComponent();
        DataContext = this;
    }

设置 DataContext 将指定应从何处获取新数据。在名为 WPF Basic Data Binding FAQ 的文章中有一些很棒的提示和信息.阅读它以更好地理解 DataContex 的用途。它是 WPF/C# 中必不可少的组件。


由于问题的更新而更新。

据我了解,您应该将 DependencyProperty.Register 的第一个参数更改为您要绑定(bind)到的属性的名称,此处为 "Header" 以及类类型的第二个参数,此处为 SomeClass。那会给你留下:

public static readonly DependencyProperty MyDependencyProperty =
    DependencyProperty.Register("Header", typeof(SomeClass), typeof(string));

但我很少使用依赖属性,所以我不确定这就是它,但它值得一试..

关于c# - WPF UserControl绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6547752/

相关文章:

c# - 在 C# 对象中显示外键对象名称的最佳实践

c# - SingleOrDefault 返回 null 时的 LINQ 新实例

c# - 在虚拟化 WPF TreeView 中滚动非常不稳定

wpf - WinForms互操作,从WinForms-> WPF拖放

c# - 如何为所有网格行设置最小高度?

c# - 具有空值的 ASP.NET MVC 属性路由

原始内存流上的 C# 数学性能

c# - 异常处理 : how granular would you go when it comes to argument validation?

c# - 将数据从我的服务添加到我的 View 模型时,为什么我的 View 没有更新?

c# - WPF ComboBox 项目在 Visibility.Collapsed 之后保留在列表中