将UIElement的属性绑定到我的UserControl属性上。

42 浏览
0 Comments

将UIElement的属性绑定到我的UserControl属性上。

我有一个文本框和一个用户控件,我该如何将文本框的Text属性绑定到用户控件中的Message属性上?

XAML:

我的属性:

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

但没有答案:

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

0
0 Comments

首先,定义自己的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绑定到自己。

解决方法:

- 确保定义的DependencyProperty的命名规则正确,应为"Property" + Property。

- 如果在自己的用户控件中编写代码,实现INotifyPropertyChanged接口,并将控件的DataContext绑定到自己。

这样就可以解决Binding UIElement property to my UserControl Property的问题。

0