代码之家  ›  专栏  ›  技术社区  ›  Guge

通过ContentControl绑定到DataTemplate中根元素的属性

  •  0
  • Guge  · 技术社区  · 15 年前

    在我的用户界面中,我有时想把标题放在用户控件之上。

    为了将来的本地化,我想在XAML中声明这些标题,所以我想让它们远离数据上下文。

    数据绑定可以从UserControl根节点上的属性集获取它们吗?

    我将问题归结为以下代码示例:

    using System.Windows;
    
    namespace WpfApplication12
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
    
                this.Person = new Author { Name = "Guge" };
    
                this.DataContext = this;
            }
    
            public object Person { get; set; }
        }
    
        public class Author
        {
            public string Name { get; set; }
        }
    }
    

    还有:

    <Window x:Class="WpfApplication12.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication12"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <DataTemplate DataType="{x:Type local:Author}">
            <Border AutomationProperties.Name="Author" BorderThickness="1" BorderBrush="Black">
                <Label Content="{Binding Name}"/>
            </Border>
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <Label x:Name="Position" Content="Author"/>
        <ContentControl x:Name="presentation" Content="{Binding Person}"/>
    </StackPanel>
    

    实际问题是:如何在“位置”标签的内容属性中使用数据绑定,从数据模板中的automationproperties.name属性中获取单词“author”?

    2 回复  |  直到 15 年前
        1
  •  0
  •   bitbonk    15 年前

    在数据对象上执行路由如何:

    public class Author
    {
        public string Name { get; set; }
        public string TypeName { get; set; } // might be better in base class Person
    }
    

    还有:

    <Window.Resources>
        <DataTemplate DataType="{x:Type local:Author}">
            <Border AutomationProperties.Name="{Binding TypeName}" 
                    BorderThickness="1" BorderBrush="Black">
                <Label Content="{Binding Name}"/>
            </Border>
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <Label x:Name="Position" Content="{Binding ElementName=presentation, Path=DataContext.TypeName}"/>
        <ContentControl x:Name="presentation" Content="{Binding Person}"/>
    </StackPanel>
    
        2
  •  0
  •   Guge    15 年前

    到目前为止,解决方案是将typename的string属性添加到ViewModel中,并用代码隐藏的automationproperties.name的内容填充它。并使用以下绑定:

    <StackPanel>
        <Label x:Name="Position" Content="{Binding Person.TypeName}"/>
        <ContentControl x:Name="presentation" Content="{Binding Person}"/>
    </StackPanel>
    

    但是,我仍然认为不使用ViewModel就可以做到这一点,我希望能够在我的数据绑定技能提高后重新讨论这个问题。