Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WPF将不同的UserControl绑定到不同的ViewModel_C#_Wpf_Xaml_Bind - Fatal编程技术网

C# WPF将不同的UserControl绑定到不同的ViewModel

C# WPF将不同的UserControl绑定到不同的ViewModel,c#,wpf,xaml,bind,C#,Wpf,Xaml,Bind,我是WPF的新手,在将两个不同的ViewModel绑定到两个UserControl时遇到了一个问题 它将附加到Tabcontrol中的两个Tabpages 我的代码片段如下所示: MainWindow.xaml <Window.Resources> <local:UserControl1Model x:Key="Control1Model" /> <local:UserControl2Model x:Key="Control2Model" />

我是WPF的新手,在将两个不同的ViewModel绑定到两个UserControl时遇到了一个问题 它将附加到Tabcontrol中的两个Tabpages

我的代码片段如下所示:

MainWindow.xaml

<Window.Resources>
    <local:UserControl1Model x:Key="Control1Model" />
    <local:UserControl2Model x:Key="Control2Model" />
</Window.Resources>

<Grid HorizontalAlignment="Left" Height="330" VerticalAlignment="Top" Width="592">
    <Grid HorizontalAlignment="Left" Height="45" Margin="0,330,-1,-45" VerticalAlignment="Top" Width="593">
        <Button Content="Button" HorizontalAlignment="Left" Margin="490,5,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    </Grid>
    <TabControl HorizontalAlignment="Left" Height="330" VerticalAlignment="Top" Width="592" >
        <TabItem x:Name="UserControl1TabItem" Header="User Control 1" >
            <Grid x:Name="UserControl1Tabpage" Background="#FFE5E5E5" Margin="0,0,-4,-2" Height="300" VerticalAlignment="Top" IsEnabled="true" >
                <local:UserControl1 VerticalAlignment="Top" DataContext="{Binding Source={StaticResource Control1Model}}" />
            </Grid>
        </TabItem>
        <TabItem x:Name="UserControl2TabItem" Header="User Control 2">
            <Grid x:Name="UserControl2Tabpage" Background="#FFE5E5E5">
                <local:UserControl2 VerticalAlignment="Top" DataContext="{Binding Source={StaticResource Control2Model}}" />
            </Grid>
        </TabItem>
    </TabControl>
</Grid>
UserControl1Model.cs

public class UserControl1Model : INotifyPropertyChanged
{
    private string _message;

    public string Message
    {
        get { return _message; }
        set
        {
            _message = value;
            OnPropertyChanged("Message");
        }
    }

    public UserControl1Model()
    {
    }

    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(string message)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(message));
        }
    }

    #region INotifyPropertyChanged Members

    // Declare the event
    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}
出于测试目的,UserControl2Model.cs的内容与UserControl1Model.cs相同

public class UserControl1Model : INotifyPropertyChanged
{
    private string _message;

    public string Message
    {
        get { return _message; }
        set
        {
            _message = value;
            OnPropertyChanged("Message");
        }
    }

    public UserControl1Model()
    {
    }

    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(string message)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(message));
        }
    }

    #region INotifyPropertyChanged Members

    // Declare the event
    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}
UserControl1.xaml

<UserControl.Resources>
    <app:UserControl1Model x:Key="Control1Model" />
</UserControl.Resources>

<Grid Margin="0,0,0,42" DataContext="{Binding Source={StaticResource Control1Model}}"> 
    <Label Content="Test:" HorizontalAlignment="Left" Margin="48,57,0,0" VerticalAlignment="Top" Width="47"/>

    <TextBox x:Name="Conrol1ModelTextbox" HorizontalAlignment="Left" Height="23" Margin="90,59,0,0" TextWrapping="Wrap" 
       Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
       VerticalAlignment="Top" Width="466" />
</Grid>
UserControl2.xaml

<UserControl.Resources>
    <app:UserControl2Model x:Key="Control2Model" />
</UserControl.Resources>

<Grid Margin="0,0,0,42" DataContext="{Binding Source={StaticResource Control2Model}}"> 
    <Label Content="Test:" HorizontalAlignment="Left" Margin="48,57,0,0" VerticalAlignment="Top" Width="47"/>

    <TextBox x:Name="Conrol2ModelTextbox" HorizontalAlignment="Left" Height="23" Margin="90,59,0,0" TextWrapping="Wrap" 
       Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
       VerticalAlignment="Top" Width="466" />
</Grid>

出于测试目的,UserControl2.xaml.cs的内容与UserControl1.xaml.cs的内容相同

public partial class UserControl1 : UserControl
{        
    public UserControl1()
    {
        InitializeComponent();
    }
}
我的问题是在MainWindow.xaml.cs中初始化的两个用户控件的初始值“Hello”和“Test”
被“绑定”到用户控件文本框中。我做错了什么或遗漏了什么?

创建ViewModelLocator。你可以在互联网上找到关于这个主题的各种网站

一个简单的例子是:

public class ViewModelLocator
{
  public UserControl1Model UserControl1Model { get; set; } = new UserControl1Model();
  public UserControl2Model UserControl2Model { get; set; } = new UserControl2Model();
  public ViewModelLocator
  {
    UserControl1Model.Message = "Hello";
    UserControl2Model.Message = "Test";  
  }
}
然后您可以在视图中使用它

<UserControl.Resources>
    <app:ViewModelLocator x:Key="ViewModelLocator" />
</UserControl.Resources>

<Grid Margin="0,0,0,42" DataContext="{Binding UserControl2Model Source={StaticResource ViewModelLocator}}"> 
    <Label Content="Test:" HorizontalAlignment="Left" Margin="48,57,0,0" VerticalAlignment="Top" Width="47"/>

    <TextBox x:Name="Conrol2ModelTextbox" HorizontalAlignment="Left" Height="23" Margin="90,59,0,0" TextWrapping="Wrap" 
       Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
       VerticalAlignment="Top" Width="466" />
</Grid>

创建ViewModelLocator。你可以在互联网上找到关于这个主题的各种网站

一个简单的例子是:

public class ViewModelLocator
{
  public UserControl1Model UserControl1Model { get; set; } = new UserControl1Model();
  public UserControl2Model UserControl2Model { get; set; } = new UserControl2Model();
  public ViewModelLocator
  {
    UserControl1Model.Message = "Hello";
    UserControl2Model.Message = "Test";  
  }
}
然后您可以在视图中使用它

<UserControl.Resources>
    <app:ViewModelLocator x:Key="ViewModelLocator" />
</UserControl.Resources>

<Grid Margin="0,0,0,42" DataContext="{Binding UserControl2Model Source={StaticResource ViewModelLocator}}"> 
    <Label Content="Test:" HorizontalAlignment="Left" Margin="48,57,0,0" VerticalAlignment="Top" Width="47"/>

    <TextBox x:Name="Conrol2ModelTextbox" HorizontalAlignment="Left" Height="23" Margin="90,59,0,0" TextWrapping="Wrap" 
       Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
       VerticalAlignment="Top" Width="466" />
</Grid>

当您像这样声明资源时

<Window.Resources>
    <local:UserControl1Model x:Key="Control1Model" />
    <local:UserControl2Model x:Key="Control2Model" />
</Window.Resources>
您还需要为主窗口设置DataContext

public MainWindow()
{
    InitializeComponent();

    this.DataContext = new MainWindowViewModel();     
}
并从UserControl XAML中删除资源。您已经在MainWindow.xaml中定义了DataContext,但是绑定应该从MainWindowViewModel中绑定

<local:UserControl1 VerticalAlignment="Top" DataContext="{Binding FirstModel}" />

当您像这样声明资源时

<Window.Resources>
    <local:UserControl1Model x:Key="Control1Model" />
    <local:UserControl2Model x:Key="Control2Model" />
</Window.Resources>
您还需要为主窗口设置DataContext

public MainWindow()
{
    InitializeComponent();

    this.DataContext = new MainWindowViewModel();     
}
并从UserControl XAML中删除资源。您已经在MainWindow.xaml中定义了DataContext,但是绑定应该从MainWindowViewModel中绑定

<local:UserControl1 VerticalAlignment="Top" DataContext="{Binding FirstModel}" />

假设我在xaml中创建这个实例,如下所示:
而不是在
MainWindow.xaml.cs
中创建。那么,如何在
MainWindow.xaml.cs
中引用此实例,例如从
MainWindowViewModel.ViewModelLocator.FirstModel.Message
获取值

像这样:

MainWindowViewModel viewModel = this.Resources["MainWindowViewModel"] as MainWindowViewModel;
//access any properties of viewModel here...
假设我在xaml中创建这个实例,如下所示:
而不是在
MainWindow.xaml.cs
中创建。那么,如何在
MainWindow.xaml.cs
中引用此实例,例如从
MainWindowViewModel.ViewModelLocator.FirstModel.Message
获取值

像这样:

MainWindowViewModel viewModel = this.Resources["MainWindowViewModel"] as MainWindowViewModel;
//access any properties of viewModel here...

您从未绑定到在MainWindow中创建的VM实例如何绑定到VM实例?你能写一些代码片段给我一些建议吗!非常感谢。您从未绑定到在MainWindow中创建的VM实例。如何绑定到VM实例?你能写一些代码片段给我一些建议吗!非常感谢。谢谢你的回答。我还有一个问题与创建MainWindowViewModel实例的位置有关。假设我在xaml中创建这个实例,如下所示:而不是在MainWindow.xaml.cs内部创建。那么,我如何在MainWindow.xaml.cs中引用此实例,例如从MainWindowViewModel.ViewModelLocator.FirstModel.Message获取值?请查看我的答案。感谢您的回答。我还有一个问题与创建MainWindowViewModel实例的位置有关。假设我在xaml中创建这个实例,如下所示:而不是在MainWindow.xaml.cs内部创建。那么,如何在MainWindow.xaml.cs中引用此实例,例如从MainWindowViewModel.ViewModelLocator.FirstModel.Message获取值?请查看我的答案。