Есть ли в любом случае привязать команду ко всем экземплярам кнопки в пользовательском элементе управления в XAML / WPF / MVVM - PullRequest
0 голосов
/ 19 октября 2018

Моя проблема в том, что у меня много кода, делающего то же самое.Все кнопки в моей панели стека запускают команду, и с помощью этой команды я хочу отправить параметр методу в моей модели представления.

У меня есть следующий код XAML, как вы можете видеть, что он до смешного повторяется:

<StackPanel x:Name="Row" Grid.Row="4">
    <Button Content="z" 
        Command="{Binding ButtonClickCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" />
    <Button Content="x" 
        Command="{Binding ButtonClickCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" />
    <Button Content="c" 
        Command="{Binding ButtonClickCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" />
    <Button Content="v" 
        Command="{Binding ButtonClickCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" />
    <Button Content="b" 
        Command="{Binding ButtonClickCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" />
    <Button Content="n" 
        Command="{Binding ButtonClickCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" />
    <Button Content="m" 
        Command="{Binding ButtonClickCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" />
</StackPanel>

Есть ли способ уменьшить количество повторяющегося кода, либо в XAML, либо в представленииМодель?

Заранее спасибо

Ответы [ 2 ]

0 голосов
/ 19 октября 2018

Простое решение, которое работает, при условии, что у вас есть кнопки и привязка команд в одном месте, или же первый ответ (увиденный ответ после моего поста) дает вам самый простой способ, поместив элемент ItemsControl и выполнив все это.

   <StackPanel x:Name="Row" Grid.Row="4">
              <StackPanel.Resources>
                  <Style TargetType="{x:Type Button}">
                      <Setter Property="Command" Value="{Binding ButtonClickCommand}" />
                      <Setter Property="CommandParameter" Value="{Binding RelativeSource={RelativeSource Self}, Path=Content}"
  />
                  </Style>
              </StackPanel.Resources>
              <Button Content="z"  />
              <Button Content="x"  />
              <Button Content="c"  />
              <Button Content="v"  />
              <Button Content="b"  />
              <Button Content="n"  />
              <Button Content="m"  />
          </StackPanel>

Надеюсь, это поможет вам:)

0 голосов
/ 19 октября 2018

Создайте список элементов в вашей ViewModel, например,

public IEnumerable<string> Values { get; set; } = new List<string> { "x", "c", "v", "..." };

И присвойте его ItemsControl

<ItemsControl x:Name="Row" Grid.Row="4" ItemsSource="{Binding Values}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding }" 
                Command="{Binding Path=DataContext.ButtonClickCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}" 
                CommandParameter="{Binding }"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

ItemsControl.ItemsPanel, который говорит, какой контейнер использовать для этихitems и ItemTemplate определяет, как должен выглядеть каждый элемент StackPanel.

Связывание внутри DataTemplate относится к string, поэтому для того, чтобы добраться до ButtonClickCommand, мы должны вернуться кItemsControl контекст.

...