0

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

我想在 XAML 中声明这些标题以供将来本地化,所以我想将它们排除在数据上下文之外。

数据绑定可以从用户控件的根节点上的属性集中获取它们吗?

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

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>

实际问题是:如何在“位置”标签的内容属性中使用数据绑定从 DataTemplate 中边框的 AutomationProperties.Name 属性中获取单词“作者”?

4

2 回答 2

0

如何通过您的数据对象进行路由:

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>
于 2010-10-08T07:35:36.753 回答
0

到目前为止的解决方案是将 TypeName 的字符串属性添加到视图模型中,并用代码隐藏中的 AutomationProperties.Name 的内容填充它。并使用以下绑定:

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

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

于 2010-10-23T12:47:34.017 回答