TreeViewItem使用用户控件和绑定

时间:2011-07-11 10:06:07

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

我在档案馆寻求帮助,但我找不到任何针对我的特定问题的具体内容。

我有一个使用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的新手,所以我还没有解决它。

谢谢!

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

在代码隐藏

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      
}

在xaml

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

以后......

<TextBlock Text="{Binding Text, ElementName=root}" />
相关问题