首页 > 解决方案 > Dependecy 属性用作源但不用作目标

问题描述

我在用户控件中有一个依赖属性。

    public ComputerListView()
    {
        InitializeComponent();

        vm = new ComputerViewModel();

        this.DataContext = vm;

        DispatcherTimer time = new DispatcherTimer(TimeSpan.FromSeconds(1), DispatcherPriority.Normal,
            delegate
            {
                  SetValue(AutoCounterProperty, vm.SimpleCounter);
            },
            Dispatcher);

    }

    public int AutoCounter
    {
        get { return (int)GetValue(AutoCounterProperty); }
        set { SetValue(AutoCounterProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Counter.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty AutoCounterProperty =
        DependencyProperty.Register("AutoCounter", typeof(int), typeof(ComputerListView), new PropertyMetadata(0));
    }

<StackPanel>
    <local:ComputerListView x:Name="computerListView" AutoCounter="{Binding VMCounter, Mode=TwoWay}"/>
    <TextBox Background="Beige" Text="{Binding VMCounter, Mode=TwoWay}"/>
    <TextBlock Background="LightCyan" Text="{Binding ElementName=computerListView, Path=AutoCounter}"/>
    <Button Content="VMCounter" Click="VMCounter_Button_Click"/>
</StackPanel>

我希望该VMCounter属性将得到更新,因为AutoCounter它将在依赖属性中运行,并且 TextBox 将从该VMCounter属性中更新,但它显示为 0,永远不会更新。

我已经使用了AutoCounter我在 TextBlock 中的方式,然后它更新得很好。

我认为 DP 的主要用途是能够像第一种情况一样用作目标属性。为什么它不能那样工作?

标签: wpfxaml

解决方案


推荐阅读