在WPF中Binding.Mode,选择默认值时,它取决于绑定的属性.
我正在寻找一些列表或一些约定或任何信息的各种控件的默认值.
我的意思是TwoWay,默认情况下属性是什么等等.任何链接,想法,想法,甚至咆哮都很受欢迎!
这是一个小的XAML片段.你会看见
<StackPanel>
<TextBox x:Name="txtValue">250</TextBox>
<Slider x:Name="slide"
Value="{Binding ElementName=txtValue, Path=Text,
Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Minimum="0" Maximum="500"></Slider>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)
如果我删除Mode=OneWayset指令(默认为双向),一切都很完美.
为什么会这样?
最初,我有以下代码:
<TextBox Text="{Binding LengthUnit, Mode=OneWay}" IsReadOnly="True" Background="{x:Static SystemColors.ControlBrush}" />
Run Code Online (Sandbox Code Playgroud)
我知道我可以定义这样的样式:
<Style TargetType="{x:Type TextBox}" x:Key="readOnlyTextBox">
<Setter Property="Background" Value="{x:Static SystemColors.ControlBrush}"></Setter>
<Setter Property="IsReadOnly" Value="True"></Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)
这样我就可以写:
<TextBox Text="{Binding LengthUnit, Mode=OneWay}" Style="{StaticResource readOnlyTextBox}" />
Run Code Online (Sandbox Code Playgroud)
因为此文本框是只读的,所以绑定模式不能是双向的.那么,是否可以使用此样式将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;
}
}
Run Code Online (Sandbox Code Playgroud) 我想以编程方式找出属性的默认绑定模式.
例如,如果我检查它TextBox.TextProperty应该是BindingMode.TwoWay,但如果ItemsControl.ItemsSourceProperty它应该是BindingMode.OneWay.
我实现了一个自定义的MarkupExtension,到目前为止我的代码中已经有了这么多:
public override object ProvideValue(IServiceProvider provider)
{
var service = provider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
if (service != null)
{
var target = service.TargetObject as DependencyObject;
var property = service.TargetProperty as DependencyProperty;
// Not sure what to do with the target and propery here...
}
}
Run Code Online (Sandbox Code Playgroud) 有什么区别:
{Binding Prop, Mode=OneTime}
Run Code Online (Sandbox Code Playgroud)
和
{Binding Prop, Mode=OneWay}
Run Code Online (Sandbox Code Playgroud)
我认为效率存在差异。任何人都可以描述绑定模式的工作原理或提供一些有关此信息的参考吗?谢谢!
binding-mode ×5
wpf ×5
binding ×3
data-binding ×2
.net ×1
c# ×1
silverlight ×1
textbox ×1
xaml ×1