没有必要为具有如此简单行为的可重用控件创建单独的ViewModel。只需在简单的UserControl中添加一些DependencyProperties和一个事件处理程序,您就可以重用逻辑并仅设置每个实例上实际不同的属性。对于UserControl XAML,您只需将TextBox连接到DependencyProperty并将Button连接到Click处理程序。
<DockPanel>
<Button Content="Reset" Click="Button_Click"/>
<TextBox Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=Text}"/>
</DockPanel>
UserControl的代码只需要定义可以在外部绑定的属性以及用于重置文本的处理程序。
public partial class ResetTextBox : UserControl
{
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(ResetTextBox),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty ResetTextProperty = DependencyProperty.Register(
"ResetText",
typeof(string),
typeof(ResetTextBox),
new UIPropertyMetadata(String.Empty));
public string ResetText
{
get { return (string)GetValue(ResetTextProperty); }
set { SetValue(ResetTextProperty, value); }
}
public ResetTextBox()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Text = ResetText;
}
}
然后用你只需要绑定到您的视图模型字符串属性和设置,应该在这既可以在这里硬编码,或绑定到其他VM属性重置应用的默认文本的控制。
<StackPanel>
<local:ResetTextBox ResetText="One" Text="{Binding Name1}"/>
<local:ResetTextBox ResetText="Two" Text="{Binding Name2}"/>
<local:ResetTextBox ResetText="Three" Text="{Binding Name3}"/>
</StackPanel>
+1表示良好的答案。但我不认为创建ViewModel类来表示模型项的说法是正确的。相反,仅根据视图和视图创建ViewModel类。如果视图需要某些模型数据,那么ViewModel将使用模型中的特定属性来满足视图的需要。因此,第一个ViewModel可以包含文本文本(如果需要,可以从Model获得),Icommand和第二个可以包含'Collection' –
Amsakanna
2010-07-23 22:46:58
感谢您的评论,但我暗示你永远不会启动* app *(而不是视图模型)与视图;你永远不会写一个应用程序'把文本放在方框中',你可以用真正的实体来写一些真正的目的。所以你需要一个Model来开始。我相信我的答案已经表明,第一类将包含文本和ICommand的属性,第二类也将是一个集合。 – 2010-07-24 07:25:07
你是对的我在这里弄错了方法。我现在看到它。但我同意ViewModels应该基于视图而不是Model来创建。 无论如何,在我的情况下,我没有一个集合的固定数量的重复控件,应该在我的模型中表示固定数量的字符串。 – Kugel 2010-07-24 13:43:53