Reputation: 3025
I happened to have the need to bind a Grid's DataContext
to a listview's SelectedItem
property
I could do that without any problem.... However, since the Listview's SelectedItem
stores an object, the XAML editor does not know the type it is working with, which causes the following warning to be displayed : "Cannot resolve Property X in data context of type 'object'"
Is there any way to specify in one of the bindings which type an object is (i searched for WPF casting but found no pertinent resources)
Here is a relevant extract of my XAML :
<ListView x:Name="ListView" ItemsSource="{Binding LoginScreens}" Grid.Column="0" Grid.Row="0" SelectionMode="Single"/>
<Grid Grid.Column="1" Grid.Row="0" DataContext="{Binding SelectedItem, ElementName=ListView}">
<Grid.RowDefinitions>
/*rows*/
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
/*Columns*/
</Grid.ColumnDefinitions>
<TextBox Grid.Row="0" Grid.Column="1" Style="{StaticResource TextBoxStyle}" Text="{Binding Name}"/>
<TextBox Grid.Row="1" Grid.Column="1" Style="{StaticResource TextBoxStyle}" Text="{Binding NameFr}"/>
<TextBox Grid.Row="2" Grid.Column="1" Style="{StaticResource TextBoxStyle}" IsEnabled="False" Text="{Binding Filename}"/>
<TextBox Grid.Row="3" Grid.Column="1" Style="{StaticResource TextBoxStyle}" IsEnabled="False" Text="{Binding SHA1}"/>
</Grid>
I tried the following syntax in the TextBox's bindings which didn't work :
<TextBox Grid.Row="0" Grid.Column="1" Style="{StaticResource TextBoxStyle}" Text="{Binding (manifestEditor:LoginScreen.Filename)}"/>
But it causes an error to be thrown about a key being null in a ListDictionary, so either i'm missing something or it is not the right way to go.
EDIT :
I'd like as much as possible to only use XAML to handle this
Upvotes: 3
Views: 1870
Reputation: 2620
Your code works fine for me. Just to add something new and useful here is another way of defining the binding to the SelectedItem:
<Grid>
<StackPanel>
<ListView x:Name="ListView" ItemsSource="{Binding LoginScreens}"
IsSynchronizedWithCurrentItem="True"
SelectionMode="Single"/>
<Grid DataContext="{Binding LoginScreens}">
<StackPanel>
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Name}"/>
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding NameFr}"/>
<TextBox Grid.Row="2" Grid.Column="1" IsEnabled="False" Text="{Binding Filename}"/>
<TextBox Grid.Row="3" Grid.Column="1" IsEnabled="False" Text="{Binding SHA1}"/>
</StackPanel>
</Grid>
</StackPanel>
</Grid>
IsSynchronizedWithCurrentItem syncs the CurrentItem of the default CollectionView of the bound collection with the SelectedItem of your control and by choosing the DataContext of the Grid as the ObservableCollection LoginScreens, you will get the updates according to the ListView selection.
Upvotes: 4
Reputation: 225
Databind the SelectedItem to a ViewModel. Databind the DataGrid's datacontext to the same ViewModel. As long as the ViewModel knows what types it's working with, all should work well.
Upvotes: 0