1

我创建了一个按钮,它应该支持自动换行。我的按钮 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;

谁能告诉我我做错了什么?请注意,事件处理程序在最初不起作用时已经实现,无法弄清楚我试图实现的功能是否需要这些事件处理程序?

期待阅读您的回复:)

4

1 回答 1

5

你的问题是你直接设置一个依赖属性(this.ButtonTextBlock.Text = NewValue)。

在您执行此操作之前, this.ButtonTextBlock.Text 的值设置为Binding. 将绑定替换为本地值会删除绑定,文本将不再响应原始绑定表达式。

代替 -this.ButtonTextBlock.Text = Value;

和 -this.ButtonTextBlock.SetCurrentValue(TextProperty, value);

这将设置值而不会破坏您的绑定

于 2013-04-19T09:19:13.997 回答