我创建了一个按钮,它应该支持自动换行。我的按钮 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" />
这完美地工作并且按钮文本正确显示。但是,当我从 C# 代码分配 ButtonText 时,文本不会更新。我正在分配变量,如下所示。
touchButton.ButtonText = navButton.Caption;
谁能告诉我我做错了什么?请注意,事件处理程序在最初不起作用时已经实现,无法弄清楚我试图实现的功能是否需要这些事件处理程序?
期待阅读您的回复:)