我正在制作类似TicTacToeGame的游戏,试图使用MVVM,但此时我遇到了一个问题。我不明白我怎么能(如果可能的话)为不同的DataTempalte元素设置不同的名称(确切地说是"按钮")。
<Window x:Class="TicTacToeCommand.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TicTacToeCommand"
mc:Ignorable="d"
Title="MainWindow" Height="500" Width="400"
Background="White"
Name="mainW">
<Window.Resources>
<Style x:Key="ButtonsStyle" TargetType="Button">
<Setter Property="Command" Value="{Binding ElementName=mainW, Path=DataContext.GetButtonPressCommand}"></Setter>
<Setter Property="Margin" Value="5"></Setter>
<Setter Property="Background" Value="Black"></Setter>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="47*"/>
<RowDefinition Height="20*"/>
</Grid.RowDefinitions>
<ItemsControl Grid.Row="0" ItemsSource="{Binding ButtonsList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Content}"
Name="b1"
Style="{StaticResource ButtonsStyle}"
CommandParameter="{Binding ElementName=b1, Path=Name}">
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="3" Columns="3" Name="uniformGrid1">
</UniformGrid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
这是我的XAML代码。此外,我试图将名称作为命令中的命令参数发送,但我总是得到"b1"名称,因为他们都得到了它,我需要他们都有不同的名称。。。
如果可能的话,在这之后我如何将这些名称发送到命令?
我将非常感谢你的帮助,请原谅我可能犯的错误。
元素名称,尤其是在模板中,对没有太大帮助
<Button Content="{Binding Content}"
Name="b1"
Style="{StaticResource ButtonsStyle}"
CommandParameter="{Binding ElementName=b1, Path=Name}">
按钮已绑定到此处的某个项目。为什么不将该项作为CommandParameter发送?
<Button Content="{Binding Content}"
Style="{StaticResource ButtonsStyle}"
CommandParameter="{Binding Path=.}">
然后在视图模型中,您可以强制转换为项类型并访问其所有属性(Content
等)