【发布时间】:2010-12-10 11:29:27
【问题描述】:
是否可以将数据绑定到“错误”的方向?我希望将自定义控件中的值绑定到我的 ViewModel。我尝试使用“OneWayToSource”模式绑定,但无法正常工作。
场景(简化):
我有一个自定义控件 (MyCustomControl),它的依赖属性是一个字符串列表:
public class MyCustomControl : Control
{
static MyCustomControl()
{
//Make sure the template in Themes/Generic.xaml is used.
DefaultStyleKeyProperty.OverrideMetadata(typeof (MyCustomControl), new FrameworkPropertyMetadata(typeof (MyCustomControl)));
//Create/Register the dependency properties.
CheckedItemsProperty = DependencyProperty.Register("MyStringList", typeof (List<string>), typeof (MyCustomControl), new FrameworkPropertyMetadata(new List<string>()));
}
public List<string> MyStringList
{
get
{
return (List<string>)GetValue(MyCustomControl.MyStringListProperty);
}
set
{
var oldValue = (List<string>)GetValue(MyCustomControl.MyStringListProperty);
var newValue = value;
SetValue(MyCustomControl.MyStringListProperty, newValue);
OnPropertyChanged(new DependencyPropertyChangedEventArgs(MyCustomControl.MyStringListProperty, oldValue, newValue));
}
}
public static readonly DependencyProperty MyStringListProperty;
}
该控件还包含操作此列表的代码。
我在具有 ViewModel 的 UserControl 中使用此自定义控件。 ViewModel 有一个属性,它也是一个字符串列表:
public List<string> MyStringsInTheViewModel
{
get
{
return _myStringsInTheViewModel;
}
set
{
if (value != _myStringsInTheViewModel)
{
_myStringsInTheViewModel = value;
OnPropertyChanged("MyStringsInTheViewModel");
}
}
}
private List<string> _myStringsInTheViewModel;
现在我想将自定义控件 (MyStringList) 中的列表绑定到 ViewModel (MyStringsInTheViewModel) 中的列表,以便在自定义控件中更改列表时,它也会在 ViewModel 中更改。我已经尝试过了,但无法让它工作......
<myns:MyCustomControl MyStringList="{Binding Path=MyStringsInTheViewModel, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}">
如何进行这样的绑定?
【问题讨论】:
-
你为什么使用
OneWayToSource?我怀疑删除Mode和UpdateSourceTrigger可能足以使绑定起作用。