У меня есть ListView
, который отображает таблицу с различными столбцами.Каждая ячейка строки в таблице содержит другой тип элемента управления;Я пытаюсь позволить пользователю редактировать данные в каждой строке, выбрав строку и дважды щелкнув по ней, чтобы сделать ячейки редактируемыми.Поэтому я смог заставить их всех работать, за исключением столбца, который содержит ComboBox
es.
XAML-код:
Это XAMLкод для ListView
.В нем около 7 столбцов, но я сосредотачиваюсь на столбце с ComboBox
es, как показано здесь.
<ListView x:Name="MyListView" IsSynchronizedWithCurrentItem="True" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,12,0,0" Height="315" Width="560" ItemsSource="{Binding People}">
<ListView.View>
<GridView>
<!-- More Grid column code here -->
<GridViewColumn Header="Fleet" Width="70">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox Name="locationCmboBx" ItemsSource="{Binding DataContext.SchoolLocations, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Mode=TwoWay}" Loaded="OnCmboBxLoad" IsEnabled="False" Width="55" HorizontalAlignment="Center"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<!-- More Grid column code here -->
</GridView>
</ListView.View>
</ListView>
C # код:
Так что здесь в кодеПозади я пытаюсь использовать VisualTreeHelper
, как рекомендовано другими, чтобы получить доступ к locationsCmboBx
( ComboBox ), вложенному в DataTemplate
, CellTemplate
и другие XAML заголовков в ListView
.
// More code before here
ListView listViewItem = (ListView)(MyListView.ItemContainerGenerator.ContainerFromItem(MyListView));
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(listViewItem);
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
ComboBox comboBox = (ComboBox)myDataTemplate.FindName("locationsCmboBx", myContentPresenter);
// More code before here
private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem)
{
return (childItem)child;
}
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
{
return childOfChild;
}
}
}
return null;
}
Так что все, что у меня есть, работает, но когда я отлаживаю код и получаю функцию FindName
, ComboBox
равен null
.В конечном итоге я хочу установить для него свойство IsEnabled
и получить SelectedValue
из locationsCmboBx
.Я верю, что что-то упустил, но не уверен в чем.Любая помощь будет оценена?