好的,我得到了一个包含ListBox的Tabcontrol。现在我的问题是我想将<TextBox x:Name="DetailTextBox" Text="{Binding Detail}"/>
绑定到列表框中的selectedItem并显示Detail
属性值。
请注意,TextBox不是TabControl的一部分,而是在另一列中。
我无法弄清楚,当有多个ListBox时,如何处理绑定,每个TabControl项中都有一个。
我的班级
public class TabViewModel
{
public string Name { get; set; }
public ObservableCollection<TabItemViewModel> Collection { get; set; }
}
public class TabItemViewModel
{
public string Title { get; set; }
public string Detail { get; set; }
}
public MainWindow()
var tabViewModels = new ObservableCollection<TabViewModel>();
tabViewModels.Add(new TabViewModel{Name = "Tab 1", Collection = new ObservableCollection<TabItemViewModel>{new TabItemViewModel{Detail = "Detail 1.1", Title = "Title 1.1"}, new TabItemViewModel{Detail = "Detail 2.2", Title = "Title 2.2"}}});
tabViewModels.Add(new TabViewModel { Name = "Tab 2", Collection = new ObservableCollection<TabItemViewModel> { new TabItemViewModel { Detail = "Detail 2.1", Title = "Title 2.1" }, new TabItemViewModel { Detail = "Detail 2.2", Title = "Title 2.2" } } });
tabViewModels.Add(new TabViewModel { Name = "Tab 3", Collection = new ObservableCollection<TabItemViewModel> { new TabItemViewModel { Detail = "Detail 3.1", Title = "Title 3.1" }, new TabItemViewModel { Detail = "Detail 3.2", Title = "Title 3.2" } } });
DataContext = tabViewModels;
MainWindow.xaml。
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*"/>
<ColumnDefinition Width="50*"/>
</Grid.ColumnDefinitions>
<TabControl ItemsSource="{Binding}" Grid.Column="0" SelectedIndex="0">
<TabControl.ItemContainerStyle>
<Style TargetType="{x:Type TabItem}">
<Setter Property="Header">
<Setter.Value>
<Binding Path="Name"/>
</Setter.Value>
</Setter>
</Style>
</TabControl.ItemContainerStyle>
<TabControl.ContentTemplate>
<DataTemplate>
<ListBox ItemsSource="{Binding Collection}">
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Title}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
<StackPanel Grid.Column="1">
<TextBox x:Name="DetailTextBox" Text="{Binding Detail}"/>
</StackPanel>
</Grid>
修改
临时解决方案 找到了让它工作的方法,但我仍在寻找纯Xaml解决方案。 添加了SelectionChange事件
<ListBox ItemsSource="{Binding Collection}" SelectionChanged="ListBox_SelectionChanged">
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
DetailTextBox.DataContext = (TabItemViewModel) e.AddedItems[0];
}
答案 0 :(得分:2)
怎么样,我很惊讶自己:-)
对您的Xaml进行这些更改。
<TabControl ItemsSource="{Binding}"
Grid.Column="0" SelectedIndex="0"
IsSynchronizedWithCurrentItem="True">
<ListBox ItemsSource="{Binding Collection}"
IsSynchronizedWithCurrentItem="True">
<TextBox x:Name="DetailTextBox"
Text="{Binding /Collection/Detail}"/>
'/'绑定到控件的CollectionView的当前所选项目。
所以上面的绑定正在向下钻取
为了实现这一点,我们需要指定IsSynchronizedWithCurrentItem="True"
以确保SelectedItem保持与每个集合的当前项保持同步。