我有一个对话框窗口,其中包含一个ListBox
ItemTemplate 包含一个扩展器。它IsExpanded
绑定到项目视图模型中的属性。的属性也绑定到项目视图模型对象中ListBoxItem
的属性。最后将 的属性绑定到视图模型中的同名属性。IsSelected
IsExpanded
SelectedItem
ListBox
这里的问题是,在显示对话框并将其设置为对话框之前设置视图模型时DataContext
,列表框中的项目被选中,展开器箭头显示它处于展开状态,但内容扩展器的不显示。
如果我在显示对话框后设置视图模型,例如。在对话框的 Loaded 处理程序中,事情按预期工作。这里发生了什么,解决它的最佳方法是什么?
对话窗口定义为:
<Window x:Class="WpfApplication1.Dialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:WpfApplication1"
Title="Dialog" Height="300" Width="300">
<Grid>
<ListBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<Expander Header="Expander" x:Name="MyExpander" IsExpanded="{Binding IsExpanded, Mode=TwoWay}">
<Rectangle Width="100" Height="20" Fill="Red" />
</Expander>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding IsExpanded, Mode=TwoWay}" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid>
以及ViewModel(为简洁起见,不包括实现):
public interface IMyViewModel : INotifyPropertyChanged
{
object SelectedItem { get; set; }
ObservableCollection<IMyItemViewModel> Items { get; }
}
public interface IMyItemViewModel : INotifyPropertyChanged
{
bool IsExpanded { get; set; }
}
然后我有一个带有按钮的简单主窗口,它的Click
处理程序定义为:
private void Button_Click(object sender, RoutedEventArgs e)
{
MyViewModel vm = new MyViewModel();
MyItemViewModel item = new MyItemViewModel();
vm.Items.Add(item);
vm.SelectedItem = item;
Dialog dialog = new Dialog();
dialog.DataContext = vm;
dialog.ShowDialog();
}
当我运行应用程序并单击按钮时,会出现对话框,展开器箭头表示它处于展开状态,但不显示其内容。单击展开器会折叠它,再次单击它会展开它,这一次会显示内容。将相同的代码直接放在主窗口而不是对话框中,但是可以正常工作。
如果我只是做 aDispatcher.BeginInvoke(new Action(() => vm.SelectedItem = item);
而不是直接设置它,事情似乎也可以工作,但这感觉有点不稳定。
可以做些什么来解决这个问题?