【发布时间】:2020-09-11 15:35:51
【问题描述】:
我已经按照这篇文章中的示例:Dependency Property is not updating my Usercontrol 并从这里下载了示例:http://www.mediafire.com/file/y1qvv6b68tjibh1/DependencyPropertyInsideUserControl.zip/file
我想要做的是在 UserControl 上添加一个新属性,该属性的值是从现有的属性 CellValue 中设置的。
所以用户控件是这样的:
<UserControl x:Class="DependencyPropertyInsideUserControl.control"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid Height="Auto" Width="Auto">
<Grid.RowDefinitions>
<RowDefinition Height="35"/>
<RowDefinition Height="35" />
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Text="{Binding Path = CellValue}" Name="textBox2" />
<TextBox Grid.Row="1" Text="{Binding Path = MyNewValue}" Name="myNewTextBox" /> <-- I have added this in
</Grid>
现在我希望 MyNewValue 在用户更新 CellValue 时自动更新。 所以我在后面的代码中做了如下操作:
添加如下:
public string MyNewValue
{
get { return (string)GetValue(MyNewValueProperty); }
set { SetValue(MyNewValueProperty, value); }
}
public static readonly DependencyProperty MyNewValueProperty =
DependencyProperty.Register("MyNewValue", typeof(string), typeof(control), new FrameworkPropertyMetadata
{
BindsTwoWayByDefault = true,
});
并在 CellValue 的处理程序中添加了对 SetValue(MyNewValueProperty, value) 的第二次调用:
public string CellValue
{
get
{
return (string)GetValue(CellValueProperty);
}
set
{
SetValue(CellValueProperty, value);
SetValue(MyNewValueProperty, value); <-- Update MyNewValueProperty whenever CellValueProperty gets updated
}
}
但它不起作用,MyNewValue 永远不会在 CellValue 发生变化时发生变化。 我只希望用户更改一个值,即 CellValue 修改另一个属性时如何更改 UserControl 中的一个属性?
【问题讨论】:
标签: c# wpf xaml user-controls