最初,我有以下代码:
<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;
}
}