首页 > 解决方案 > 链接的 UserControl 依赖项属性不同步

问题描述

在我的项目中,我有两个自定义用户控件。一个简单的数字控件称为NumericUpDown. 还有一个名为NumericUpDownGrid. 两者都定义了依赖属性,如下所示:

对于NumericUpDownXAML 代码是:

<Grid>
        <Grid>
            <StackPanel Orientation="Horizontal">
                <TextBox x:Name="txtNum" x:FieldModifier="private" Margin="5,5,0,5" Width="50" Text="{Binding Value,Mode=TwoWay}"/>
                <Button x:Name="cmdUp" x:FieldModifier="private" Margin="5,5,0,5" Content="˄" Width="20" Click="cmdUp_Click" />
                <Button x:Name="cmdDown" x:FieldModifier="private" Margin="0,5,0,5"  Content="˅" Width="20" Click="cmdDown_Click" />
            </StackPanel>
        </Grid>
    </Grid>

并且 C# 属性定义如下:

public static readonly DependencyProperty ValueDependencyProperty = DependencyProperty.Register("Value", typeof(double), typeof(NumericUpDown));

public double Value {
    get { return (double)GetValue(ValueDependencyProperty); }
    set { SetValue(ValueDependencyProperty, value); }
}

public NumericUpDown() {
    InitializeComponent();
    Value = 0.0;
    this.DataContext = this;
}

基于上述简单控件,我需要制作这些控件的网格。但是,我可以绑定一个值数组,而不是解析每个元素,这样我就不必编写所有更新的代码。

因此,这些组件的网格代码如下:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition />
    </Grid.RowDefinitions>

    <StackPanel Grid.Row="0" Grid.Column="0" Orientation="Horizontal">
        <Label Width="20">A</Label>
        <control:NumericUpDown x:Name="A" Value="{Binding Values[0],Mode=TwoWay}"></control:NumericUpDown>
    </StackPanel>
    <StackPanel Grid.Row="0" Grid.Column="1" Orientation="Horizontal">
        <Label Width="20">B</Label>
        <control:NumericUpDown x:Name="B" Value="{Binding Values[1],Mode=TwoWay}"></control:NumericUpDown>
    </StackPanel>
    <StackPanel Grid.Row="0" Grid.Column="2" Orientation="Horizontal">
        <Label Width="20">C</Label>
        <control:NumericUpDown x:Name="C" Value="{Binding Values[2],Mode=TwoWay}"></control:NumericUpDown>
    </StackPanel>
</Grid>

同样,依赖属性和构造函数的 C# 代码是:

public static readonly DependencyProperty ValuesDependencyProperty = DependencyProperty.Register("Values", typeof(double[]), typeof(NumericUpDownGrid));
public double[] Values {
    get { return (double[])GetValue(ValuesDependencyProperty); }
    set { SetValue(ValuesDependencyProperty, value); }
}

public NumericUpDownGrid() {
    Values = new double[] { 0.5, 0.0, 0.0 };
    InitializeComponent();
    this.DataContext = this;
}

现在我希望当我按下 cmdUp 或 cmdDown 按钮时,单曲内的值变化NumericUpDown将反映在我的相关数组中NumericUpDownGrid。因为那些是有界的。但这种情况并非如此。任何帮助将非常感激。

我需要这个,因为它将把它绑定到来NumericUpDownGrid自我的应用程序更高链的数据。我期望这个绑定在绑定时会向下传播到单个元素。此外,单个的任何更改NumericUpDown都应传播回更高级别使用的数组。

标签: c#wpfxamldata-binding

解决方案


推荐阅读