【发布时间】:2011-07-21 19:23:10
【问题描述】:
最初,我有以下代码:
<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,因为我的属性是 get-only,而不是因为我将 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;
}
}
【问题讨论】:
-
@milliu,如果它是 ReadOnly 那么你为什么要让它成为 OneWay?恕我直言,为单个属性创建单独的控件不是一个健康的想法。
-
@Prince,正如我的更新所示,OneWay 是由于我的 get-only 属性。
标签: wpf binding textbox binding-mode