首页 文章

TreeViewItem使用用户控件和绑定

提问于
浏览
0

我搜索了档案馆的帮助,但我找不到任何针对我的特定问题的具体内容 .

我有一个使用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;
}

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

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

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

谢谢!

2 回答

  • 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}" />
    
  • 0

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

相关问题