【问题标题】:Binding UIElement property to my UserControl Property将 UIElement 属性绑定到我的 UserControl 属性
【发布时间】:2016-04-30 19:29:03
【问题描述】:

我有文本框和用户控件,如何将文本框属性文本绑定到用户控件中的属性消息?

XAML:

<TextBox Name="txtMessages"/>

<myControl:MyAppBar x:Name="appBar" Message="{Binding ElementName=txtMessages,  Path=Text, Mode=TwoWay}"  Grid.Row="3"/>

还有我的财产:

     public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
 private string message;
        public string Message
        {
            get
            {
                return message;
            }
            set
            {
                message = value;
                RaisePropertyChanged("Message");
            }
        }

但这对我不起作用。 我得到错误:

找不到与此错误代码相关的文本。

我也试试这个: 我试试看:

public static readonly DependencyProperty UserControlTextProperty = DependencyProperty.Register(
        "Message",
        typeof(int),
        typeof(ImageList),
        new PropertyMetadata(0, new PropertyChangedCallback(MyControl.MyAppBar.OnUserControlTextPropertyChanged))
        );

 public string Message
        {
            get { return (string)GetValue(UserControlTextProperty); }
            set { SetValue(UserControlTextProperty, value); }
        }

但不支持: “找不到与此错误代码相关的文本。”

【问题讨论】:

  • 您必须在您的用户控件中为Message 注册一个DependencyPropertymsdn.microsoft.com/library/…
  • @FlatEric 更新问题
  • 您正在为所有者类型 ImageList 注册它,但您的控件似乎是 MyAppBar 类型。并且依赖属性类型为int,而CLR属性类型为string
  • @FlatEric 谢谢所以匹配它的工作!;)另一个问题,如果不难的话。 INotifyPropertyChanged 和 DepedencyProperty 有什么区别?
  • 这个问题有几个答案,例如:stackoverflow.com/questions/3551204/…

标签: c# xaml binding properties user-controls


【解决方案1】:

首先,定义自己的 DependencyProperty 需要保持命名规则。上面代码中“UserControlTextProperty”不被识别为属性名应该是“Property”+Property如“MessageProperty”。

public static readonly DependencyProperty MessageProperty = DependencyProperty.Register("Message", typeof(int), typeof(ImageList), new PropertyMetadata(0, new PropertyChangedCallback(MyControl.MyAppBar.OnUserControlTextPropertyChanged)));

public string Message
{
    get { return (string)GetValue(MessageProperty); }
    set { SetValue(MessageProperty, value); }
}

它将被识别为常规依赖属性。 如果您在自己的用户控件中编写,则不必分离其 ViewModel,而是让您的控件实现 INotifyPropertyChanged 接口并将控件的 DataContext 绑定到自身。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 2012-05-23
    相关资源
    最近更新 更多