【问题标题】:How do I bind TwoWay between a CheckBox in a UserControl and the ViewModel in the wider scope?如何在 UserControl 中的 CheckBox 和更广泛范围内的 ViewModel 之间绑定 TwoWay?
【发布时间】:2013-05-07 20:40:38
【问题描述】:

我有一个UserControl,上面有一个CheckBox。当我在 XAML 主页面上使用 UserControl 时,我想将控件上的属性绑定到我的 ViewModel 上的属性,例如

<myUserControl BtnIsBlacklisted="{Binding IsBlacklisted, Mode=TwoWay}" />

IsBlacklisted 更改时,我希望我的复选框也更改,反之亦然。

这就是我所拥有的,

public static readonly DependencyProperty BtnIsBlacklistedProperty =
        DependencyProperty.Register("BtnIsBlacklisted", 
            typeof(bool), 
            typeof(MyUserControl),
            new PropertyMetadata(false, new 
            PropertyChangedCallback(BtnIsBlacklistedPropertyChanged))
        );

    private static void BtnIsBlacklistedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // ... do something here ...
    }

    public bool BtnIsBlacklisted
    {
        get { return (bool)GetValue(BtnIsBlacklistedProperty); }
        set { SetValue(BtnIsBlacklistedProperty, value); }
    }

我的 UserControl 有这个用于 CheckBox,

<CheckBox x:Name="myCheckBox" 
    ...
IsChecked="{Binding Path=BtnIsBlacklisted, 
        ElementName=UserControl, 
        Converter={StaticResource BoolToNotBool}, 
        Mode=TwoWay}" />

我的 ViewModel 对象上的属性如下,

    public bool IsBlacklisted
    {
        get 
        {
            return App.VM.BlacklistedRetailers.Contains(this.Retailer);
        }
        set
        {
            if (value)
            {
                App.VM.BlacklistedRetailers.Add(this.Retailer);
            }
            else
            {
                while (App.VM.BlacklistedRetailers.Contains(this.Retailer))
                {
                    App.VM.BlacklistedRetailers.Remove(this.Retailer);
                }
            }
            this.NotifyPropertyChanged("IsBlacklisted");
        }
    }

BlacklistedRetailers 更改的唯一方法是通过上面的 set 方法,因此无需从那里触发 NotifyPropertyChanged ...

我已经尝试了其他问题中的许多建议,即

  1. 使用依赖属性
  2. 包括Mode=TwoWay
  3. 使用在包含网格上设置的自引用 DataContext 绑定 UserControl(这也不起作用)。

但是这些都不起作用。

一些最后的笔记:

  • 这是针对 Windows Phone 7.5 项目的
  • 编辑:一种方式绑定也不起作用,似乎绑定到UserControl自己的属性有问题

【问题讨论】:

  • 你的 BoolToNotBool 转换器也是 TwoWay 吗?
  • 是的。我现在对它做了更多的工作,我发现如果我直接从 UserControl XAML 绑定而不是通过绑定,它就可以工作。 UserControl 属性,例如IsChecked="{Binding IsBlacklisted, Converter={StaticResource BoolToNotBool}, Mode=TwoWay}" 但是这不是很通用,因为它需要知道 UserControl 中的外部 ViewModel 的名称......我还发现 OneWay 绑定不能正常工作,属性只是因为我设置它们而被更新DependencyPropertyChanged 事件处理程序 - 问题已更新 ...

标签: windows-phone-7 xaml binding user-controls


【解决方案1】:

ElementName Binding 匹配与设置绑定的元素同名范围内的 x:Name 值。显示的代码不足以说明,但您使用的是“UserControl”,我猜它没有设置为元素的名称,而是用于尝试匹配类型。如果在模板中声明了CheckBoxElementName 也可能无法解析。

【讨论】:

  • 你知道了,我在开头的UserControl 元素中设置了x:Name="thisUserControl",并在绑定中将其称为ElementName=thisUserControl,它可以工作。谢谢!
猜你喜欢
  • 2012-05-01
  • 1970-01-01
  • 2011-12-14
  • 2013-04-12
  • 2020-05-10
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多