Skip to main content
 首页 » 编程设计

c#之不显示代码中依赖属性的更改

2024年02月13日11del

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

谁能告诉我我做错了什么? 请注意,事件处理程序在最初无法正常工作时已经实现,无法确定我尝试实现的功能是否需要这些事件处理程序?

期待阅读您的回复:)

请您参考如下方法:

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

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

替换 - this.ButtonTextBlock.Text = Value;

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

这将在不破坏绑定(bind)的情况下设置值