【问题标题】:How to bind multiple user controls?如何绑定多个用户控件?
【发布时间】:2014-12-18 13:34:08
【问题描述】:

我创建了以下用户控件:

<UserControl x:Class="TextBinder" ...>
    <TextBox Text="{Binding ????}" />
</UserControl>

现在我在 MainWindow 中使用了我的用户控件两次。然后将 MainWindow 绑定到我的 ViewModel(我设置了 DataContext)。现在的问题是:如何将我的用户控件绑定到 user_controlViewModel?

在我的 ViewModel 中,我创建了两个对象,我们称它们为 UC_1 和 UC_2,它们包含不同的文本,我想将它们绑定到我的 MainWindow 中各自的用户控件。

我应该放什么????

注意:请不要将 mu TextBox 简化为一个用户控件中的双文本框。这不是我想要的,因为在我的现实生活示例中,我拥有的内容不仅仅是文本框,而且用户控件应该在一个视图中多次使用。

谢谢!

【问题讨论】:

  • 在你的用户控件中定义依赖属性。
  • 所以你的MainWindow 将DataContext 设置为ViewModel 如果是这种情况,那么你的&lt;UserControl.DataContext="{Binding UC_1}"/&gt; 然后你的&lt;TextBox Text="{Binding propertyOnYourUC_1}"/&gt; 试试,没有DependencyProperty。 HTH

标签: c# wpf mvvm


【解决方案1】:

我给了你一个笼统的答案:

在“真实(您想与具有不同属性名称的不同视图模型一起使用的用户控件)”用户控件中,您只绑定到您自己的 DependencyProperties,然后您可以使用 ElementName 或 RelativeSource 绑定 并且您应该永远不要在 UserControl 中设置 DataContext。

 <UserControl x:Name="myRealUC" x:class="MyUserControl">
   <TextBox Text="{Binding ElementName=myRealUC, Path=MyOwnDPIDeclaredInMyUc, Path=TwoWay}"/>
 <UserControl>

如果您这样做,您可以轻松地在任何视图中使用此用户控件,例如:

<myControls:MyUserControl MyOwnDPIDeclaredInMyUc="{Binding MyPropertyInMyViewmodel}"/>

为了完整性:依赖属性

    public readonly static DependencyProperty MyOwnDPIDeclaredInMyUcProperty = DependencyProperty.Register(
    "MyOwnDPIDeclaredInMyUc", typeof(string), typeof(MyUserControl), new PropertyMetadata(""));

    public bool MyOwnDPIDeclaredInMyUc
    {
        get { return (string)GetValue(MyOwnDPIDeclaredInMyUcProperty); }
        set { SetValue(MyOwnDPIDeclaredInMyUcProperty, value); }
    }

【讨论】:

    【解决方案2】:

    没错,你需要在你的 UserControl 中声明一个依赖属性:

    public partial class TextBinder:UserControl
    {
    
      public static readonly DependencyProperty textproperty = 
      DependencyProperty.Register("Text", typeof(string), typeof(TextBinder));
    
      public string Text
      {
        get
        {
            return this.GetValue(textproperty) as string;
        }
        set
        {
            this.SetValue(textproperty,value);
        }
      }
    }
    

    然后,您可以通过这种方式在窗口中使用您的用户控件:

    <YourNamespace:TextBinder Text={Binding ViewModelProperty}/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 2018-11-25
      相关资源
      最近更新 更多