【发布时间】:2012-03-29 13:12:01
【问题描述】:
我在用户控件中有一个文本框和一个按钮,它会在按钮单击中打开一个窗口以选择某些内容并放入文本框中: 像这样:
string myProperty;
public string MyProperty
{
get
{
return myProperty;
}
set
{
myProperty= value;
RaisePropertyChanged("MyProperty");
}
}
public ICommand buttonClickCommand
{
get { return new RelayCommand(ShowItemView); }
}
void ShowItemView()
{
var ItemViewModel = new ItemViewModel();
var ItemView = new ItemView();
ItemView .DataContext = ItemViewModel ;
ItemView .ShowDialog();
if (ItemViewModel .SelectedItem != null)
myProperty= ItemViewModel .SelectedItem.Name;
}
现在我想在一个窗口中创建两个用户控件实例,并将它们的文本框绑定到窗口视图模型的两个属性,所以我为它创建一个依赖属性,如下所示:
public static readonly DependencyProperty OperandTextValueProperty = DependencyProperty.Register("OperandTextValue",
typeof(string),
typeof(DefaultSpecItemControl),
new FrameworkPropertyMetadata()
{
PropertyChangedCallback = OnOperandTextValue,
BindsTwoWayByDefault = true
});
public string OperandTextValue
{
get
{
return (string)GetValue(OperandTextValueProperty);
}
set
{
SetValue(OperandTextValueProperty, value);
}
}
并将其绑定到窗口视图模型中的属性,但我不知道如何将其绑定到用户控件的视图模型,在这种情况下将其绑定到控件视图模型中的 MyProperty。所以
1:有没有办法将用户控件的dependencyProperty绑定到它自己的viewmodel?
2:我走对了吗?
提前致谢。
【问题讨论】:
-
如果
ItemView是一个能够取消/关闭的对话框,请使用下一行: if (ItemView .ShowDialog() == true) if (ItemViewModel .SelectedItem != null) myProperty= ItemViewModel 。选定项目名称;或与此类似。 -
为什么你认为你必须在你的窗口中定义一个 DependenyProperty,如果你遵循 MVVM 模式,那么你最好在 Windows 的 ViewModel 中只定义简单的属性。然后这些属性应该从相关的 UserControl 的 ViewModel 返回值。您的问题我不清楚,请解释得更多更好。
-
@Sam:我没有在Window中定义dependencyProperty,我在usercontrol中定义它。我想将它绑定到userControl的viewmodel。
-
@stukselbax:我不明白你的意思!我认为我的问题不清楚!这是因为我的英语不好!:我的用户控件中有一个名为 OperandTextValue 的依赖属性和一个属性在 usercontrol 的 viewmodel 中命名为 Myproperty,现在我想将它们绑定在一起!!因为我必须在 usercontrol 的 viewmodel 中设置它的值。
标签: wpf data-binding binding mvvm mvvm-light