c# - 分配有值绑定(bind)的依赖属性不起作用

标签 c# windows-store-apps winrt-xaml dependency-properties windows-8.1

我有一个带有依赖属性的用户控件。

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/

相关文章:

c# - C#套接字服务器发送问题

c# - LINQ的以下两个查询有什么不同

c# - 如何从 Windows 商店应用程序启动桌面应用程序?

xaml - 在 VisualStateManager (WinRT XAML) 中更改 ItemTemplate 中控件的属性

c# - 如何修复错误 : Cannot call the requested method (GetBasicPropertiesAsync). 之前对此方法的调用正在挂起

c# - Random.value 到 bool?

c# - 我可以在 RichTextBox 中插入一个带有进度条的按钮吗

xaml - UWP Xaml GridViewItem : Remove margin

windows-store-apps - 签名工具错误 : The specified algorithm cannot be used or is invalid

c# - 防止键盘打开时页面屏幕向上滚动(C#-XAML-Windows Store App)