相关疑难解决方法(0)

使用MVVM在MainWindow上绑定UserControl视图模型

我是WPF和MVVM的新手,我正在尝试学习WPF如何与MVVM一起使用。为此,我制作了以下示例

UserControl1.xaml

<StackPanel>
        <TextBox   Text="{Binding MyString}" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

UserControl1ViewModel.cs

class UserControl1ViewModel
{
     public string MyString { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

MainWindow.xaml

<StackPanel>
        <local:UserControl1 DataContext="{Binding UC1Property}"/>  //tried binding the Usercontrol1VM obj on MainWindowVM
        <Button Command="{Binding ShowMeOne}" Height="30" Content="ShowOne"/>
        <Button Command="{Binding ShowMeAnother}" Height="30" Content="ShowAnother" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

MainWindow.xaml.cs

public MainWindow()
{
   InitializeComponent();
   this.DataContext = new MainWindowViewModel();
}
Run Code Online (Sandbox Code Playgroud)

MainWindowViewModel.cs

class MainWindowViewModel
{
    public MainWindowViewModel()
    {
        ShowMeOne = new RelayCommand(Prompt_ShowMeOne);
        ShowMeAnother = new RelayCommand(Prompt_ShowMeAnother);
        UC1Property.MyString = "Initial";
    }

    private void Prompt_ShowMeAnother(object obj)
    {
        global::System.Windows.MessageBox.Show("Another Should …
Run Code Online (Sandbox Code Playgroud)

c# wpf xaml user-controls mvvm

2
推荐指数
1
解决办法
4071
查看次数

标签 统计

c# ×1

mvvm ×1

user-controls ×1

wpf ×1

xaml ×1