c# - 链接的 UserControl 依赖项属性不同步
问题描述
在我的项目中,我有两个自定义用户控件。一个简单的数字控件称为NumericUpDown
. 还有一个名为NumericUpDownGrid
. 两者都定义了依赖属性,如下所示:
对于NumericUpDown
XAML 代码是:
<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
都应传播回更高级别使用的数组。
解决方案
推荐阅读
- python - 几个小时后,Django 图像和内容消失了
- android - 如何解谜
values.xml 中的错误? - python - 将 argparse 与格式化的位置参数一起使用
- mongodb - 如何创建具有可变日期的部分索引?
- winforms - 循环没有完全显示所有元素
- python - 如何使用 environtment.yml 文件将带有 pip 的本地库安装到 conda 环境?
- javascript - 使用纯(香草)JS 在画布的 X、Y 坐标处触发点击事件
- html - 如何修复“可下载字体:被消毒剂拒绝”
- java - 将字符串输入数组,然后将字符串拆分为单个字符数组
- jquery - 使用 html/css 的正文高度和水平滚动