gpt4 book ai didi

WPF 文本框 : How to change binding mode default to OneWay?

转载 作者:行者123 更新时间:2023-12-04 11:15:14 24 4
gpt4 key购买 nike

最初,我有以下代码:

<TextBox Text="{Binding LengthUnit, Mode=OneWay}" IsReadOnly="True" Background="{x:Static SystemColors.ControlBrush}" />

我知道我可以定义这样的风格:
<Style TargetType="{x:Type TextBox}" x:Key="readOnlyTextBox">
<Setter Property="Background" Value="{x:Static SystemColors.ControlBrush}"></Setter>
<Setter Property="IsReadOnly" Value="True"></Setter>
</Style>

这样我就可以写:
<TextBox Text="{Binding LengthUnit, Mode=OneWay}" Style="{StaticResource readOnlyTextBox}" />

因为这个文本框是只读的,所以绑定(bind)模式不能是双向的。那么,是否可以将 OneWay 绑定(bind)设置为具有这种样式的 TextBox 的默认值?

编辑:我需要将绑定(bind)模式更改为 OneWay,因为我的属性是 get-only,而不是因为我将 TextBox 标记为只读。但是,如果可能,我仍然想将文本框的默认绑定(bind)模式更改为 OneWay。

这是我遵循您的建议的代码,但它不起作用。我错过了什么吗?
public class ReadOnlyTextBox : TextBox
{
static ReadOnlyTextBox()
{
TextBox.TextProperty.OverrideMetadata(typeof(ReadOnlyTextBox),
new FrameworkPropertyMetadata() { BindsTwoWayByDefault = false, Journal = true, DefaultUpdateSourceTrigger = UpdateSourceTrigger.Explicit });
}
public ReadOnlyTextBox()
{
base.Background = SystemColors.ControlBrush;
base.IsReadOnly = true;
}
}

最佳答案

Because this textbox is readonly, the binding mode cannot be twoway.



为什么不? IsReadOnly 将阻止用户修改文本,从而修改属性。只要确保不要在代码中修改 Text 属性。

如果子类化 TextBox,则可以防止绑定(bind)属性更新。如果这样做,您可以覆盖 TextBox.Text 依赖属性元数据。
public class TextBoxEx : TextBox
{
public TextBoxEx() : base() { }

static TextBoxEx()
{
TextBox.TextProperty.OverrideMetadata(typeof(TextBoxEx),
new FrameworkPropertyMetadata() { BindsTwoWayByDefault = false, Journal = true,
DefaultUpdateSourceTrigger = System.Windows.Data.UpdateSourceTrigger.Explicit });
}

}

出于某种原因,将 BindsTwoWayByDefault 更改为 false 对我不起作用,但您可以将 DefaultUpdateSourceTrigger 设置为 Explicit,这意味着除非通过代码更新绑定(bind)的属性,否则不会更新绑定(bind)属性,从而有效地进行绑定(bind) OneWay。

关于WPF 文本框 : How to change binding mode default to OneWay?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5414075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com