沒有必要爲具有如此簡單行爲的可重用控件創建單獨的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