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
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With