C# 如何使DependencyProperty正确强制值';绑定的类型
我有一个C# 如何使DependencyProperty正确强制值';绑定的类型,c#,wpf,xaml,binding,C#,Wpf,Xaml,Binding,我有一个ItemsControl子类,其行为类似于选择器,但它不能是选择器的子类,因为所选项不一定在Items集合中。所以我不得不重新实现很多选择器的东西 我的类有一个SelectedValuePath属性。如果该属性有值,我将创建一个绑定,以便在SelectedItem更改时,“SelectedItem.”+SelectedValuePath的值被分配给SelectedValue。只要消费者将mySelectedValue绑定到与SelectedItem上的value属性类型相同的属性,这一点
ItemsControl
子类,其行为类似于选择器
,但它不能是选择器
的子类,因为所选项不一定在Items
集合中。所以我不得不重新实现很多选择器的东西
我的类有一个SelectedValuePath
属性。如果该属性有值,我将创建一个绑定,以便在SelectedItem
更改时,“SelectedItem.”+SelectedValuePath
的值被分配给SelectedValue
。只要消费者将mySelectedValue
绑定到与SelectedItem
上的value属性类型相同的属性,这一点就可以完美实现
问题是:
但是,如果选定项具有用作值属性的int-ID
属性,并且SelectedValue
绑定到视图模型上的null-SelectedID
属性,则绑定将无法在视图模型上设置属性,除非SelectedItem
为null
我注意到WPFComboBox
类没有这个问题,因此它必须是可以解决的,而不需要使用者提供值转换器。我尝试了一个强制值回调
,但这对我没有任何帮助。它不知道目标类型。它没有关于接收值的绑定的信息
什么是组合框。SelectedValue
做了我没有做的事
我相当熟悉IValueConverter
以及在使用控件时如何将值转换器添加到XAML中的绑定中。我不需要帮助。我在问是否有人知道ComboBox.SelectedValue
上的任何绑定如何将int
转换为int?
,而无需控件的使用者向绑定添加值转换器 正如我所预料的,问题并不是我所预料的那样。没有类型转换问题
Binding binding = new Binding("SelectedItem." + SelectedValuePath);
binding.Mode = BindingMode.OneWay;
binding.Source = this;
BindingOperations.SetBinding(this, MenuComboBox.SelectedValueProperty, binding);
看来这个问题是我班的内部问题。我正在用绑定更新SelectedValue
Binding binding = new Binding("SelectedItem." + SelectedValuePath);
binding.Mode = BindingMode.OneWay;
binding.Source = this;
BindingOperations.SetBinding(this, MenuComboBox.SelectedValueProperty, binding);
这似乎干扰了消费者与SelectedValue
的双向绑定
我有一个BindingTarget
类,它派生自DependencyObject
。它公开一个名为Value
的dependencProperty
,并在Value
更改时触发事件。我已经编写了它,将值转发到“只读”的DependencyPropertySelectionBoxItem
,其中setter受到保护。因此,我使用了一个私有的BindingTarget
实例作为目标,并在其ValueChanged
处理程序中设置SelectedValue
,而不是从“SelectedItem.”+SelectedValuePath
创建绑定,并将SelectedValue
作为上述目标。消费者的绑定现在按预期工作
// The type argument to BindingTarget is the type of the property.
_selectedValueBindingTarget = new BindingTarget<Object>();
_selectedValueBindingTarget.ValueChanged += (s, e2) =>
{
SelectedValue = e2.NewValue;
};
Binding binding = new Binding("SelectedItem." + SelectedValuePath);
binding.Mode = BindingMode.OneWay;
binding.Source = this;
BindingOperations.SetBinding(_selectedValueBindingTarget,
BindingTarget<Object>.ValueProperty, binding);
//BindingTarget的类型参数是属性的类型。
_selectedValueBindingTarget=新建BindingTarget();
_selectedValueBindingTarget.ValueChanged+=(s,e2)=>
{
SelectedValue=e2.NewValue;
};
绑定绑定=新绑定(“SelectedItem.”+SelectedValuePath);
binding.Mode=BindingMode.OneWay;
binding.Source=this;
BindingOperations.SetBinding(_selectedValueBindingTarget,
BindingTarget.ValueProperty,绑定);