最初,我有以下代码:
<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}" />
由于该文本框是只读的,因此绑定模式不能是双向的。那么,是否可以将 OneWay 绑定设置为具有这种样式的 TextBox 的默认绑定?
编辑:我需要将绑定模式更改为 OneWay,因为我的属性是仅获取的,而不是因为我将 TextBox 标记为只读。但是,如果可能的话,我仍然想将文本框的默认绑定模式更改为 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;
}
}