WPF:依赖关系属性绑定问题



我正在使用自定义控件,其扩展状态依赖于从外部传递的参数。代码如下:

mycontrol.xaml:

<Expander x:Name="Expander" Grid.Row="1" IsExpanded="True">

mycontrol.xaml.cs:

public partial class myControl: UserControl{
public myControl()
    {
        InitializeComponent();       
    }
public static readonly DependencyProperty IsExpandAllProperty =
            DependencyProperty.Register("IsExpandAll", typeof(bool), typeof(myControl), new PropertyMetadata(new PropertyChangedCallback(OnIsExpandAllChanged)));
public bool IsExpandAll
        {
            get { return (bool)GetValue(IsExpandAllProperty); }
            set
            {
                SetValue(IsExpandAllProperty, value);
            }
        }
private static void OnIsExpandAllChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            myControl rv = sender as myControl;                
            rv.Expander.IsExpanded = System.Convert.ToBoolean(e.NewValue.ToString());
        }

XAML外部:

<DataTemplate>
  <view:myControl IsExpandAll="{Binding ExpandAllItems}"/>
</DataTemplate>
<Button Click="Button_Click"></Button>

外部ViewModel:

 private bool _expandAllItems = true;
 public bool ExpandAllItems
    {
        get { return _expandAllItems; }
        set
        {
            _expandAllItems= value;
            OnPropertyChanged("ExpandAllItems");
        }
    }

xaml.cs

private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        vm.ExpandAllItems= !vm.ExpandAllItems;
    }

i使用按钮单击事件更改ExplianalLitems值,但是在调试时,我发现从未调用ISExpandall属性设置器,MyControl中的扩展器无法更新。

我整理了一些代码来探索这里发生的事情。我有一个USERCONTROL和一个toggletton。显然,这只是一个实验,因此他们做得不多。因为我希望通过绑定我绑定到在togglebutton上的结合来驱动DP的变化。这实际上是一个布尔吗?所以我使我的DP成为一个布尔?匹配。

在Mainwindow中,只需绑定切换键盘的结合:

    <StackPanel>
        <local:UserControl1 IsExpandAll="{Binding ElementName=tb, Path=IsChecked}"/>
        <ToggleButton Name="tb" Content="Expandall"/>
    </StackPanel>

我的usercontrol1只有一个网格 - 唯一的目的是探索此DP

    public UserControl1()
    {
        InitializeComponent();
    }

    public bool? IsExpandAll
    {
        get { return (bool?)GetValue(IsExpandAllProperty); }
        set {
            SetValue(IsExpandAllProperty, value);
        }
    }
    public static readonly DependencyProperty IsExpandAllProperty =
        DependencyProperty.Register("IsExpandAll", typeof(bool?), typeof(UserControl1),   new PropertyMetadata(new PropertyChangedCallback(OnIsExpandAllChanged)));
    private static void OnIsExpandAllChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        UserControl1 rv = sender as UserControl1;
        Debugger.Break();
       // rv.Expander.IsExpanded = System.Convert.ToBoolean(e.NewValue.ToString());
    }

当我将其旋转时,它首先碰到休息时间,因为设置了DP。继续...单击togglebutton,然后再次击中休息时间。删除该断裂点,并在设置器上放置一个断点。这一点永远不会击中。原因是bitings不使用二阶。

最新更新