如何解决如何更改 ListBox 的 IsVisible 属性?
我正在制作一个简单的图书编辑器。
在书籍编辑窗口中,我希望主题和子主题按层次顺序显示,因此我制作了一个带有复杂数据模板的 ItemsControl 来显示它们。我现在拥有的是:
主题是按钮,如果单击相应的主题按钮(就像它是一个下拉列表),我希望子主题的列表框可见。
问题是我正在使用 MVVM,我不能在 OnClick 事件中更改 ListBox 的 IsVisible 属性。
如何在不破坏和 MVVM 模式的情况下做到这一点?
这是我的 XAML 代码:
<ScrollViewer>
<Grid ColumnDefinitions="auto,*" RowDefinitions="auto">
<ItemsControl Grid.Column="0" Grid.Row="0" Items="{Binding Book.Themes}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Button Name="kekw" Content="{Binding Name}" />
<ListBox Items="{Binding Subthemes}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</ScrollViewer>
这是视图模型:
public class EditBookViewModel
{
private Book book;
public Book Book
{
get
{
return book;
}
set
{
book = value;
}
}
public EditBookViewModel(string name,string path)
{
book = new Book(name,path);
book.Themes = new LinkedList<Theme>();
book.Themes.AddLast(new Theme("Theme 1","Page 1"));
book.Themes.AddLast(new Theme("Theme 2","Page 2"));
book.Themes.AddLast(new Theme("Theme 3","Page 3"));
foreach(Theme t in book.Themes)
{
t.Subthemes = new LinkedList<Subtheme>();
t.Subthemes.AddLast(new Subtheme("Subtheme 1","Page 1"));
t.Subthemes.AddLast(new Subtheme("Subtheme 2","Page 2"));
t.Subthemes.AddLast(new Subtheme("Subtheme 3","Page 3"));
}
}
}
解决方法
我怀疑您在询问有关 WPF 数据绑定的问题。 我是 Xamarin.Forms 开发人员,如果我为 Xamarin.Forms 做这件事,我可以建议我会怎么做。
-
首先,更新“Theme”类以拥有一个 bool 属性来控制是否应显示或隐藏子主题。 (确保该类实现 INotifyPropertyChanged,如果您使用的是 ReactiveUI,则可以从 ReactiveObject 继承);
-
在您的 VM 中创建一个命令,并将
<Button Name="kekw" Content="{Binding Name}" />
绑定到该命令以更新布尔属性值。 (以及绑定到主题的 CommandParameter。在 Xamarin.Forms 中,它是“.”); -
将 ListBox.IsVisible 绑定到该布尔属性。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。