如何解决链接的UserControl依赖项属性不同步
在我的项目中,我有两个自定义用户控件。一个简单的数字控件称为NumericUpDown
。还有一个名为NumericUpDownGrid
的数控网格。两者都定义了依赖项属性,如下所示:
对于NumericUpDown
,XAML代码为:
<Grid>
<Grid>
<StackPanel Orientation="Horizontal">
<TextBox x:Name="txtNum" x:FieldModifier="private" Margin="5,5,5" Width="50" Text="{Binding Value,Mode=TwoWay}"/>
<Button x:Name="cmdUp" x:FieldModifier="private" Margin="5,5" Content="˄" Width="20" Click="cmdUp_Click" />
<Button x:Name="cmdDown" x:FieldModifier="private" Margin="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
所做的任何更改都应传播回更高级别使用的数组。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。