手动添加按钮作为窗口命令时,分隔符正常显示:
<controls:MetroWindow.RightWindowCommands>
<controls:WindowCommands ShowSeparators="True">
<Button Content="Button1" />
<Button Content="Button2" />
</controls:WindowCommands>
</controls:MetroWindow.RightWindowCommands>
当尝试使用 ItemsControl 在 XAML 中动态创建按钮作为窗口命令时,我无法正确显示分隔符。除了边距/填充之外,按钮本身看起来是正确的,当分隔符固定时,边距/填充可能会被修复。
这是我的 XAML:
<controls:MetroWindow.RightWindowCommands>
<controls:WindowCommands ShowSeparators="True">
<ItemsControl ItemsSource="{Binding GamesViewModel.Games}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type entities:Game}">
<Button Content="{Binding Name}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</controls:WindowCommands>
</controls:MetroWindow.RightWindowCommands>
有人能发现我做错了什么吗?我认为这可能与我设置的 ItemsPanel 有关,但我必须这样做才能使按钮水平。也许有一个我要重写的样式/模板?
这个代码隐藏版本确实有效,但我宁愿通过 XAML 来完成:
foreach (Game game in ((MainViewModel)DataContext).GamesViewModel.Games)
WindowCommands.Items.Add(new Button { Content = game.Name });
最佳答案
我想你已经注意到了这个问题,但没有意识到! WindowCommands
本身就是一个ItemsControl
,因此只需给它一个ItemsSource
,它就会被排序。
关键是提供它 WindowCommandsItem
而不是你的 View 模型(这真的感觉像是 0.13 alpha 系列中的一个错误,我在其中进行了测试,因为如果内存允许的话,它过去在没有这种特殊转换的情况下也可以工作.)
这是我测试过的代码:
XAML 位:
<controls:MetroWindow.DataContext>
<wpfApplication1:ViewModel />
</controls:MetroWindow.DataContext>
<controls:MetroWindow.Resources>
<DataTemplate DataType="{x:Type wpfApplication1:Model}">
<Button Content="{Binding Name}" />
</DataTemplate>
<wpfApplication1:ModelToWindowCommandsItemConverter x:Key="Converter" />
</controls:MetroWindow.Resources>
<controls:MetroWindow.RightWindowCommands>
<controls:WindowCommands ItemsSource="{Binding Commands, Converter={StaticResource Converter}}" />
</controls:MetroWindow.RightWindowCommands>
使用的转换器代码:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{ return ((IEnumerable<Model>)value).Select(x => new WindowCommandsItem { Content = x }); }
View 模型:
public class ViewModel
{
public ObservableCollection<Model> Commands { get; } = new ObservableCollection<Model>
{
new Model { Name = "Skyrim" },
new Model { Name = "Fallout 4" },
new Model { Name = "Fallout NV" }
};
}
型号:
public class Model
{
public string Name { get; set; }
}
结果:
关于c# - 在 MahApps.Metro 中使用数据绑定(bind) ItemsControl 时显示 WindowCommands 的分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36752189/