我有一个带有依赖属性的用户控件。
public sealed partial class PenMenu : UserControl, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public bool ExpandCollapse
{
get
{
return false;
}
set
{
//code
}
}
public static readonly DependencyProperty ExpandCollapseProperty = DependencyProperty.Register("ExpandCollapse", typeof(bool), typeof(PenMenu), null);
//some more code
}
我在 XAML 页面中赋值如下:
<Controls:PenMenu x:Name="penMenu" Opened="Menu_Opened"
ExpandCollapse="{Binding PenMenuVisible}" />
但它没有命中用户控件中 ExpandCollapse 属性的 GET-SET 部分。 所以我将 bool 添加到 bool 转换器只是为了检查通过绑定(bind)传递的值,例如:
<Controls:PenMenu x:Name="penMenu" Opened="Menu_Opened"
ExpandCollapse="{Binding PenMenuVisible, Converter={StaticResource booleanToBooleanConverter}}" />
在 Converter 中使用断点,我看到传递的值是正确的。 它没有分配给依赖属性的可能原因是什么?
同样在 XAML 页面中,如果我说:
<Controls:PenMenu x:Name="penMenu" Opened="Menu_Opened"
ExpandCollapse="true"/>
然后它命中用户控件中 ExpandCollapse 属性的 GET-SET 部分。 我卡住了。这很奇怪。请帮忙。
最佳答案
这很令人沮丧,不是吗?首先,包含一个更改的事件处理程序。像这样:
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(string),
typeof(MyControl), new PropertyMetadata(string.Empty, Changed));
private static void Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var c = d as MyControl;
// now, do something
}
然后,请阅读这篇文章,这样您就会发现有比那一个更多的陷阱:http://blog.jerrynixon.com/2013/07/solved-two-way-binding-inside-user.html
祝你好运!
关于c# - 分配有值绑定(bind)的依赖属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20080902/