Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind datatemplate in a resource dictionary

Tags:

c#

styles

wpf

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

I have a simple class

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

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

<ListBox ItemsSource="{Binding AList}">

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>

This works great.

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

How can I do that ?

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.

Thanks for help

like image 621
cdie Avatar asked Apr 21 '15 15:04

cdie


1 Answers

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>

In MainWindow.xaml refer it

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

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; }
    }
like image 163
lerner1225 Avatar answered Sep 18 '22 01:09

lerner1225