【问题标题】:TreeViewItem using User Control and bindingTreeViewItem 使用用户控件和绑定
【发布时间】:2011-10-02 16:14:24
【问题描述】:

我搜索了档案寻求帮助,但找不到任何足够具体的内容来解决我的特定问题。

我有一个使用 MVVM 绑定数据的 TreeView,一切看起来都很好。我想扩展功能,以便我认为对 TreeView 项目使用用户控件会很好。

这是 TreeViewItems 使用的分层数据模板的 XAML 代码:

        <HierarchicalDataTemplate
          DataType="{x:Type vm:SiteViewModel}" 
          ItemsSource="{Binding Children}">
          <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding SiteName}"/>
         </StackPanel>
        </HierarchicalDataTemplate>

我想用我的用户控件替换 TextBlock:

        <uc:MyTextBlock InternalText="{Binding SiteName}"/>

用户控件(目前)只包含另一个 TextBlock,并且有一个名为 InternalText 的依赖属性,即

  <TextBlock Text="{Binding Path=InternalText}" />

我将用户控件的构造函数中的 DataContext 设置为自身:

public MyTextBlock ()
{
  InitializeComponent();
  DataContext = this;
}

这不起作用,但是如果我只是更改模板以指定静态文本,它似乎可以正常工作:

        <uc:MyTextBlock InternalText="Some site name"/>

那么如何让绑定的数据传递给用户控件呢?这可能很简单,但我是 WPF 新手,所以我还没有解决。

谢谢!

【问题讨论】:

    标签: wpf data-binding mvvm user-controls treeview


    【解决方案1】:

    InternalText 似乎不是依赖属性。尝试将其转换为一个。

    【讨论】:

      【解决方案2】:

      在代码隐藏中

      public class MyUserControl : UserControl
      {
          #region Text
          /// <summary>
          /// The <see cref="DependencyProperty"/> for <see cref="Text"/>.
          /// </summary>
          public static readonly DependencyProperty TextProperty =
              DependencyProperty.Register(
                  RunningPropertyName,
                  typeof(string),
                  typeof(MyUserControl ),
                  new UIPropertyMetadata(null));
      
          /// <summary>
          /// The name of the <see cref="Text"/> <see cref="DependencyProperty"/>.
          /// </summary>
          public const string TextPropertyName = "Text";
      
          /// <summary>
          /// The text to display
          /// </summary>
          public string Text
          {
              get { return (string)GetValue(TextProperty ); }
              set { SetValue(TextProperty , value); }
          }
          #endregion      
      }
      

      在xml中

      <UserControl x:Class="Derp.MyUserControl" 
                   x:Name="root"
                   SnippingXamlForBrevity="true"
      

      以后……

      <TextBlock Text="{Binding Text, ElementName=root}" />
      

      【讨论】:

      • 威尔,你是明星!自上周以来,我一直在研究这个问题,但进展甚微。非常感谢。现在我只想了解 为什么 它有效!我猜它是 ElementName=root 所以我现在要看看我的 WPF 书籍。
      • @ChrisTrollen:DP 是在类上定义的。此类的公共属性位于 xaml 中 UserControl 定义的根目录中。因此,您可以通过以某种方式引用 UserControl 的根节点来访问绑定中的这些公共属性。您可以通过给它命名 x:Name="something" 或使用相对源 {Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}} 来做到这一点。
      • 啊,对 - 谢谢。我曾尝试使用 RelativeSource,但我没想过将 AncestorType 设置为用户控件本身。
      猜你喜欢
      • 2020-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      • 2010-12-20
      相关资源
      最近更新 更多