不显示来自代码的依赖项属性的更改
本文关键字:属性 依赖 代码 显示 | 更新日期: 2023-09-27 18:10:10
我创建了一个按钮,它应该支持文字换行。这个按钮的XAML代码如下所示:
<Button x:Class="POS.TouchScreen.UI.Elements.TouchButtonWPF"
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" Height="23" HorizontalAlignment="Left" Name="buttonGrid" VerticalAlignment="Top" Width="75" BorderBrush="#FF8A97A9" Margin="4"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<TextBlock Name="ButtonTextBlock"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Text="{Binding ButtonText, Mode=TwoWay}"
TextWrapping="Wrap">
</TextBlock>
</Button>
我已经实现了如下所示的属性:
public static readonly DependencyProperty ButtonTextProperty =
DependencyProperty.Register("ButtonText", typeof(string), typeof(TouchButtonWPF), new UIPropertyMetadata("Button",new PropertyChangedCallback(OnButtonTextChanged), new CoerceValueCallback(OnCoerceButtonText)));
private static object OnCoerceButtonText(DependencyObject o, object value)
{
TouchButtonWPF button = o as TouchButtonWPF;
if (button != null)
return button.OnCoerceButtonText((string)value);
else
return value;
}
protected virtual string OnCoerceButtonText(string value)
{
return value;
}
private static void OnButtonTextChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
TouchButtonWPF button = o as TouchButtonWPF;
if (button != null)
button.OnButtonTextChanged((string)e.NewValue, (string) e.OldValue);
}
protected virtual void OnButtonTextChanged(string NewValue, string OldValue)
{
this.ButtonTextBlock.Text = NewValue;
}
public string ButtonText
{
get { return (string)GetValue(ButtonTextProperty); }
set { SetValue(ButtonTextProperty, value); }
}
插入一个TouchButtonWPF的实例,如下所示
<tse:TouchButtonWPF ButtonText="OK" FontSize="16" Height="77" HorizontalAlignment="Left"x:Name="buttonOk" Width="85" />
这工作完美,按钮文本显示正确。然而,当我分配ButtonText从c#代码,文本不更新。我将按如下所示对变量进行赋值。
touchButton.ButtonText = navButton.Caption;
谁能告诉我我做错了什么?请注意,事件处理程序已经实现时,它没有工作最初,不能弄清楚这些事件处理程序是否需要在所有的功能,我试图达到?期待您的回复:)
你的问题是你直接设置了一个依赖属性(this.ButtonTextBlock.Text = NewValue
)。
在此之前,this. buttontextblock . text的值被设置为Binding
。用本地值替换绑定将删除绑定,并且文本将不再响应原始绑定表达式。
replace - this.ButtonTextBlock.Text = Value;
with - this.ButtonTextBlock.SetCurrentValue(TextProperty, value);
这将设置值,而不会破坏你的绑定