日期:2014-05-17  浏览次数:21083 次

MVVM DelegateCommand<T>的一个不理解的地方
 public ICommand TexCommand
       {
           get
           {
               return new DelegateCommand<TextBox>(tb =>
               {
                     tb.Text="这个问题"; //出现tb 未实例化,也就是说tb=null               
               });
           }
       } 
      //XAML
  <my:RibbonButton  Command="{Binding TexCommand}" CommandParameter="{Binding ElementName=tb}"  Margin="805,39,0,0" Content="添加" Height="22" VerticalAlignment="Top" HorizontalAlignment="Left" Width="67" Style="{DynamicResource Button}" VerticalContentAlignment="Center" />
红色的地方怎么绑定?也就是CommandParameter绑定问题
绑定数据类没有问题,但怎绑定控件对象?

------解决方案--------------------
你这个绑定方法,是反其道而行之。本来ViewModel中应该是纯数据逻辑,把界面控件代进去,是违反了MVVM数据驱动的原则。

而且这个绑定也无法实现。因为要实现绑定,必须把红字改为 
CommandParameter={Binding Path=tb,RelativeSource={RelativeSource AncestorLevel=1,AncestorType=Window}}" 

然而tb它本身不是public的,二它也是一个字段而非属性。