2016-04-03 32 views
0

我正在做類似TicTacToeGame的事情,試圖使用MVVM,在這一點上我遇到了一個問題。我不明白我怎麼可能(如果它甚至可能),爲不同的DataTempalte元素(確切地說是「按鈕」)設置不同的名稱。如何設置不同的名稱到DataTemplate元素?

<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」的名稱,因爲他們都得到它,我需要他們都有不同的名稱...

如果在這之後我可以將這些名字發送給命令?

我將非常感謝您的幫助,請提前請諒解可能的錯誤。

回答

0

元素的名稱,尤其是在模板,不利於很多

<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等)

+0

是的,我可以這樣做,但是這是不是違反MVVM的,發送按鈕觀看模型? – kotki

+0

但是仍然有辦法給我的元素(b1,b2,b3 ...)賦予不同的名稱嗎? – kotki

+0

@kotki,您在視圖模型中使用了'ButtonsList'。 CommandParameter將是該列表的單個元素。如果第一部分可以接受,第二部分是一樣的。關於名稱:我沒有試圖做到這一點,簡單的試圖說,名稱不支持MarkupExtension喜歡綁定 – ASh

相關問題