WPF中两个用户控件之间的交互,而不使用MVVM

时间:2014-07-29 16:58:10

标签: c# wpf xaml user-controls

我的应用程序中有两个UserControls,它们都位于MainWindow。现在我需要在这两者之间进行交互,这样当我点击Button中的UserControl1时,TextTextBlock的{​​{1}}属性就会发生变化。

如果没有MVVM,我怎样才能做到这一点?我很乐意看到MVVM解决方案,但如果它是完整的,因为我对它是全新的,而且非常压倒性。

主窗口:

UserControl2

的UserControl1:

<Window x:Class="WpfApplication23.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        xmlns:wpfApplication23="clr-namespace:WpfApplication23">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <wpfApplication23:UserControl1/>
        <wpfApplication23:UserControl2 Grid.Row="1"/>
    </Grid>
</Window> 

UserControl2:

<UserControl x:Class="WpfApplication23.UserControl1"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Grid>
        <Button Content="Change Text"
                Width="200"
                Height="80"
                Click="ButtonBase_OnClick"/>
    </Grid>
</UserControl>

点击按钮的事件:

<UserControl x:Class="WpfApplication23.UserControl2"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <TextBox Width="100" Height="20"/>
    </Grid>
</UserControl>

1 个答案:

答案 0 :(得分:1)

要在没有 MVVM的情况下执行此操作,您需要执行以下操作:

  1. 设置&#34; UpdateText&#34;等事件。在第一个用户控件上,使用按钮的单击方法引发此事件。

    public event Action<string> UpdateText;
    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
       // Access the TextBlock in UserControl2 and Change its Text to "Hello World"
       if (UpdateText != null)
           UpdateText("HelloWorld");
    }
    
  2. 收听MainWindow中的事件,然后调用第二个用户控件上的函数来更新文本块。类似的东西:

    public MainWindow()
    {
        InitializeComponent();
    
        myUserControl1.UpdateText += HandleUpdateText;
    }
    
    private void HandleUpdateText(String newText)
    {
        myUserControl2.SetText(newText);
    }
    
  3. 现在正确答案是使用MVVM,但是所需的代码示例对于StackOverflow来说太长了。不过我会提供一些步骤:

    1. 在&#34; Text&#34;的第二个用户控件上设置DependencyProperty属性,并绑定到它:

      <UserControl x:Class="WpfApplication23.UserControl2"
               xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
               xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
          <Grid>
             <TextBox Width="100" Height="20" Text="{Binding ControlText}"/>
          </Grid>
      </UserControl>
      
    2. 在第一个用户控件上放置ICommand依赖项属性,该控件将在按钮单击时调用。在MainWindow上绑定一个函数,将ControlText属性设置为参数对象。

    3. 可能不是最好的&#34;第一个MVVM&#34;示例,因为它需要一些高级概念(命令和依赖属性),但它不应该难以实现。