C# 如何将字符串和命令从父组件传递到子组件

C# 如何将字符串和命令从父组件传递到子组件,c#,wpf,xaml,mvvm,custom-controls,C#,Wpf,Xaml,Mvvm,Custom Controls,我使用Prism作为WPF的MVVM容器,我想在父组件中定义一系列命令,然后让子组件执行不同的命令 我如何写作才能成功 //父控件 //vm 公共DelegateCommand TestJumpOtherTabCommand{get;set;} 公共DelegateCommand TestModifyModelDtoCommand{get;set;} 设计自定义用户控件时,可以定义依赖项属性。转到控件后面的代码,并添加下面的代码。我为要在TextBlock中绑定的文本定义Text依赖属

我使用Prism作为WPF的MVVM容器,我想在父组件中定义一系列命令,然后让子组件执行不同的命令

我如何写作才能成功

//父控件
//vm
公共DelegateCommand TestJumpOtherTabCommand{get;set;}
公共DelegateCommand TestModifyModelDtoCommand{get;set;}


设计自定义用户控件时,可以定义依赖项属性。转到控件后面的代码,并添加下面的代码。我为要在
TextBlock
中绑定的文本定义
Text
依赖属性,并为
按钮定义
命令
依赖属性

public partial class TestUserControl1 : UserControl
{
   public static readonly DependencyProperty TextProperty =
       DependencyProperty.Register(nameof(Text), typeof(string), typeof(TestUserControl1));

   public static readonly DependencyProperty CommandProperty =
      DependencyProperty.Register(nameof(Command), typeof(ICommand), typeof(TestUserControl1));

   public TestUserControl1()
   {
      InitializeComponent();
   }

   public string Text
   {
      get => (string)GetValue(TextProperty);
      set => SetValue(TextProperty, value);
   }

   public ICommand Command
   {
      get => (ICommand)GetValue(CommandProperty);
      set => SetValue(CommandProperty, value);
   }
}
在用户控件XAML中,请添加列或行,因为它是
文本块
按钮
将在
网格
的同一单元格中重叠(只有一个可见,另一个被遮挡)。此外,添加与自定义控件的绑定一起使用的绑定。这将目标属性绑定到用户控件中定义的依赖项属性

<UserControl x:Class="WpfApp1.TestUserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:YourApp">
   <Grid>
      <Grid.ColumnDefinitions>
         <ColumnDefinition/>
         <ColumnDefinition/>
      </Grid.ColumnDefinitions>
      <TextBlock Grid.Column="0" Text="{Binding Text, RelativeSource={RelativeSource AncestorType={x:Type local:TestUserControl1}}}"/>
      <Button Grid.Column="1" Command="{Binding Command, RelativeSource={RelativeSource AncestorType={x:Type local:TestUserControl1}}}"/>
   </Grid>
</UserControl>

最后,在父控件中设置或绑定用户控件的依赖项属性

<StackPanel>
   <local:TestUserControl1 Text="Hello" Command="{Binding TestJumpOtherTabCommand}"/>
   <local:TestUserControl1  Text="World" Command="{Binding TestModifyModelDtoCommand}"/>
</StackPanel>

在继续实施您自己的控制之前,您应该阅读以下有价值的资源。它们将提供关于依赖属性是什么以及如何定义或使用它们的基础知识


如果所有操作都正确,则ViewModel应位于窗口的数据上下文中。嵌套的UI元素几乎总是从父容器继承数据上下文。因此,如果实现正确,您应该在UserControl的数据上下文中有一个WindowViewModel。绑定到它的命令应该不会有任何问题。如果有问题,那么就不可能从你的解释中确定问题的原因。不要使解决方案过于复杂化。UserControl的主要功能是表示数据上下文。首先,必须确保其正确传输。添加额外的DependentcyProperty对于某种视觉效果(视图中的交互)更好。非常感谢。所以它是可以实现的。