如何在资源字典中绑定数据模板 [英] How do I bind datatemplate in a resource dictionary

查看:21
本文介绍了如何在资源字典中绑定数据模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的元素绑定在字典中定义的数据模板中.让我们简单点.

I'm trying to bind my elements in a datatemplate that is define in dictionary. Let's make it simple.

我有一个简单的类

public class A { public string Data {get;set} }

我有一个包含 ListBox 的简单视图,ItemSources 是 A 类的列表:

I have a simple view that contains a ListBox, with ItemSources is a list of class A :

<ListBox ItemsSource="{Binding AList}">

重点是,当我直接在视图中定义 Itemplate 时,bind 有效:

The point is, when I define Itemplate in view directly, bind works :

<ListBox.ItemTemplate>
   <DataTemplate >
      <TextBlock Text="{Binding Data}" />
      <Rectangle Fill="Red" Height="10" Width="10"/>
   </DataTemplate>
 </ListBox.ItemTemplate>

这很好用.

但是当我在资源字典中定义这个 ItemTemplate 时,绑定不起作用?

But when I define this ItemTemplate in resource Dictionary, binding doesn't works ?

我该怎么做?

PS:这是一个简单的例子来解释我的问题,不要告诉我重写 toString 函数使其工作或使用 classe 模板,我的真实情况比这更复杂.

PS : This is a simple example to explain my problem, don't tell me to override toString function to make it works or use classe template, my real case is very more complexe than this.

感谢帮助

推荐答案

新建一个 Dictionary1.xaml

Create a new Dictionary1.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DataTemplate x:Key="dataTemplate">
        <StackPanel>
            <TextBlock Text="{Binding Data}" />
            <Rectangle Fill="Red" Height="10" Width="10"/>
        </StackPanel>
    </DataTemplate>
</ResourceDictionary>

在 MainWindow.xaml 中引用它

In MainWindow.xaml refer it

<Window.Resources>
    <ResourceDictionary Source="Dictionary1.xaml" />
</Window.Resources>
<ListBox Name="lst" ItemTemplate="{StaticResource dataTemplate}"></ListBox>

MainWindow.cs:

MainWindow.cs:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            var observable = new ObservableCollection<Test>();
            observable.Add(new Test("A"));
            observable.Add(new Test("B"));
            observable.Add(new Test("C"));
            this.lst.ItemsSource = observable;
        }
    }

    public class Test
    {
        public Test(string dateTime)
        {
            this.Data = dateTime;
        }

        public string Data { get; set; }
    }

这篇关于如何在资源字典中绑定数据模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆