如何在ViewModel中获取Button的内容?

时间:2014-01-23 08:24:24

标签: c# button mvvm

我有一个命令设置为viewModel的按钮。运行时填充值的按钮。 任何人都可以帮我在viewModel中获取按钮内容吗?

4个按钮在运行时具有4个不同的值集,并且基于按钮单击我将采取行动。说出4个按钮第二个按钮是点击然后我将减去100分。如果单击第4个按钮,我将在scrore中添加40。这100和40是按钮内容。

<Button Height="110" Width="230" Content="{Binding Path=ListOfValues[1]}" />
<Button Height="110" Width="230" Content="{Binding Path=ListOfValues[2]}" />
<Button Height="110" Width="230" Content="{Binding Path=ListOfValues[3]}" />
<Button Height="110" Width="230" Content="{Binding Path=ListOfValues[4]}" />

有人可以帮我在viewModel的运行时获取按钮值吗?

由于

2 个答案:

答案 0 :(得分:1)

如果这是针对WPF的 - 有这样的帮助吗?

的Xaml

<Window x:Class="WpfCommandTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.Resources>
        <RoutedUICommand x:Key="DoSomethingCommand" Text="Do Something" />
    </Grid.Resources>
    <Grid.CommandBindings>
        <CommandBinding Command="{StaticResource DoSomethingCommand}" Executed="OnDoSomethingExecuted" />
    </Grid.CommandBindings>
    <Grid.RowDefinitions>
        <RowDefinition Height="30" />
        <RowDefinition Height="30" />
        <RowDefinition Height="30" />
    </Grid.RowDefinitions>
    <!-- Bind the commandParameter to the button content -->
    <Button Grid.Row="0" Content="Button1" Command="{StaticResource DoSomethingCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" />
    <Button Grid.Row="1" Content="Button2" Command="{StaticResource DoSomethingCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" />
    <Button Grid.Row="2" Content="Button3" Command="{StaticResource DoSomethingCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" />
</Grid>

代码背后:

namespace WpfCommandTest

{ 使用System.Windows; 使用System.Windows.Input;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }


    private void OnDoSomethingExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        //Look at e.Parameter   <---!!!This line gives you the value of button content
    }
}

}

想法是使用命令参数...

答案 1 :(得分:1)

在按钮的命令绑定时,提供命令参数作为按钮的内容

CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}