在Viewmodel中访问UI控件

时间:2016-06-22 14:42:56

标签: wpf mvvm

我有按钮的Stackpanel如下,

<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0 10 0 0" Name="mystack">
    <Button Width="30" Name="btn1" Height="30" Content="1" Margin="10"/>
    <Button Width="30"  Height="30" Content="2" Margin="10"/>
    <Button Width="30"  Height="30" Content="3" Margin="10"/>
    <Button Width="30" Height="30" Content="4" Margin="10"/>
</StackPanel> 

如何将这些按钮设为单个对象并在viewmodel中使用它? 因为我必须使用我的viewmodel属性检查每个按钮“Content”..

2 个答案:

答案 0 :(得分:1)

您必须创建一个绑定。

Content={Binding SomePropertyInYourViewModel, UpdateSourceTrigger=PropertyChanged}}

答案 1 :(得分:0)

您需要将按钮命令和按钮命令参数添加到按钮

<Button Content="Button1" Command="{StaticResource DoSomethingCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}" />

此链接可以帮助您How to get the Content of Button in ViewModel?

这是如何在MVVM中添加命令

    public class ViewModelBase
    {
      public ViewModelBase()
      {
       _canExecute = true;
      }
      private ICommand _doSomethingCommand;
      public ICommand DoSomethingCommand
      {
        get
        {
         return _doSomethingCommand ?? (_doSomethingCommand = new CommandHandler(() => MyAction(), _canExecute));
         }
      }
       private bool _canExecute;
       public void MyAction()
       {

       }
     }
     public class CommandHandler : ICommand
     {
       private Action _action;
       private bool _canExecute;
        public CommandHandler(Action action, bool canExecute)
        {
         _action = action;
         _canExecute = canExecute;
         }

         public bool CanExecute(object parameter)
        {
         return _canExecute;
         }

         public event EventHandler CanExecuteChanged;

         public void Execute(object parameter)
         {
             _action();
          }
        }