Reputation: 2097
I have a data template like this
public class DefaultDataTemplate : DataTemplate
{
public string Name
{
get;
set;
}
}
and I am using in xaml like this
<!-- Default DataTemplate -->
<DataTemplate x:Key="DefaultDataTemplate">
<Grid Margin="4" MinHeight="25">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" FontWeight="Bold" />
</Grid>
</DataTemplate>
I want to do binding with the "Name" Property of my datatemplate ,but right now its binded to my List view item's property named "Name".Can anybody help for the correct way or syntax
Upvotes: 1
Views: 104
Reputation: 50672
You are not using the template, you just gave the template the same key name as the class.
Also, the custom data template should have dependency properties to bind to.
Do you actually mean to do this:
<ListBox ItemsSource="{Binding Persons}">
<ListBox.DataTemplate>
<DataTemplate >
<Grid Margin="4" MinHeight="25">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Name" FontWeight="Bold" />
<TextBox Margin="8,0" Grid.Column="1" Text="{Binding Name}" />
</Grid>
</DataTemplate>
</ListBox.DataTemplate>
</ListBox>
Or perhaps
<Window.Resources>
<DataTemplate x:Key="DefaultDataTemplate">
<Grid Margin="4" MinHeight="25">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Name" FontWeight="Bold" />
<TextBox Margin="8,0" Grid.Column="1" Text="{Binding Name}" />
</Grid>
</DataTemplate>
</Window.Resources>
<ListBox ItemsSource="{Binding Persons}" DataTemplate="{StaticResource DefaultDataTemplate}"/>
Assuming the Person class has a property Name and the Persons property is an Observable<Person>
Upvotes: 1
Reputation: 43596
The DataContext
for a DataTemplate
is the DataObject it is templating, you will have to bind back to the DataTemplate
or in this case DefaultDataTemplate
to access the property.
Try:
Text="{Binding Name, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataTemplate}}}
or
Text="{Binding Name, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type myNamespace:DefaultDataTemplate }}}
Upvotes: 1