2016-06-22 101 views
0

我的StackPanel有如下按鈕訪問UI控件,在視圖模型

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

如何使這些按鈕爲單個對象和使用,在視圖模型?
因爲我要檢查每一個按鈕,「內容」與我的視圖模型屬性..

+2

您應該*從不*訪問視圖模型中的UI控件,它會打破模式。 –

+0

是的,但必須做檢查.. –

+0

你應該只是綁定感興趣的屬性(如'Content')並與該數據交互,而不是直接控制。 –

回答

0

你需要按鈕命令和按鈕命令參數添加到該按鈕

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

這個鏈接可以幫助你How to get the Content of Button in ViewModel?

這是如何在MVVM

add命令
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(); 
      } 
     } 
+0

謝謝@Hady Allam –

+0

如何獲取viewmodel中的命令值?該示例在後面的代碼中取值.. –

+0

我編輯了示例 –

0

你將不得不從頭創建inding。

Content={Binding SomePropertyInYourViewModel, UpdateSourceTrigger=PropertyChanged}} 
+0

謝謝@Hypenate –