2012-04-18 1 views
0

Я пытаюсь создать шаблонное управление кнопками с привязкой к привязке для видимости, всплывающей подсказки и команды. Связывание видимости работает, как и всплывающая подсказка, но команда не работает. Другой процесс отвечает за введение в viewmodel и связывание его с представлением, а другие привязки данных работают, поэтому я уверен, что он работает правильно.Databinding to Command в Silverlight Templated Button control

В словаре ресурсов:

<Converters:BoolToVisibilityConverter x:Key="boolVisibilityConverter" /> 

<Style TargetType="local:ImageButton"> 
    <Setter Property="Visibility" Value="{Binding FallbackValue=Visible, Path=ToolIsAvailable, Converter={StaticResource boolVisibilityConverter} }"/> 
    <Setter Property="Command" Value="{Binding ButtonCommand}"/> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="local:ImageButton"> 
       <Grid> 
       <Image Source="{TemplateBinding Image}" 
         ToolTipService.ToolTip="{Binding ToolName}" /> 
       </Grid> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

шаблонного управления

public class MyButton: ImageButton 
{ 
    public MyButton(MyCommandViewModel viewmodel) 
    { 
     this.DefaultStyleKey = typeof(ImageButton); 
     this.Image = new BitmapImage(new Uri("/MyProject;component/Themes/myimage.png", UriKind.Relative)); 
       this.DataContext = viewmodel; 
    } 

} 

и в модели представления

public MyCommandViewModel() 
     : base("My Tool", true) 
    { 
    } 


    public class CommandViewModel 
    { 
    public CommandViewModel(string toolName, bool isAvailable) 
    { 
        ToolIsAvailable = isAvailable; 
        ToolName = toolName; 
     _buttoncommand = new DelegateCommand(() => 
     { 
      ExecuteCommand(); 
     }, 
     () => { return CanExecute; }); 
    } 

    private bool _canExecute = true; 
    public bool CanExecute 
    { 
     get { return _canExecute; } 
     set 
     { 
      _canExecute = value; 
      OnPropertyChanged("CanExecute"); 
      if (_command != null) _command.RaiseCanExecuteChanged(); 
     } 
    } 

    private DelegateCommand _buttoncommand; 
    public ICommand ButtonCommand 
    { 
     get { return _buttoncommand; } 
    } 
    protected virtual void ExecuteCommand() 
    { 
    } 
    public bool ToolIsAvailable 
    { 
     get { return _toolIsReady; } 
     set { _toolIsReady = value; OnPropertyChanged("ToolIsAvailable"); } 
    } 
    public string ToolName 
    { 
     get { return _toolName; } 
     set { _toolName = value; OnPropertyChanged("ToolName"); } 
    } 
     } 

Почему другие DataBindings функционируют должным образом, но не данные команды связывание. Я нашел этот аналогичный пост Overriding a templated Button's Command in WPF Нужно ли вместо этого использовать шаблон управления сеткой и использовать RoutedCommands? Я не уверен, что понимаю, почему Silverlight рассматривает привязку Command, отличную от остальных, поэтому я подозреваю, что у меня просто ошибка в коде.

ответ

0

Особо ищет работу с данными datacontext?

Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.ButtonCommand}" 
+0

Изменение кода в \t \t не похоже в любом случае – nicoleeschmidt

+0

@nicoleeschmidt Вы пытались установить CanExecute для немедленного возвращения истины? – Josh

+0

нет, это не помогает. Я изменил команду _buttoncommand = new DelegateCommand (() => { ExecuteCommand(); }, () => {return true;}); – nicoleeschmidt

0

Это было мое решение. Используя тот же commandviewmodel, как указано выше, и такой же MyCommandViewModel

<Style TargetType="local:ImageButton"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="local:ImageButton"> 
       <Grid> 
       <Image Source="{TemplateBinding Image}" /> 
       </Grid> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

привязки данных теперь делается в пользовательский элемент управления

<UserControl x:Class="SilverlightApplication11.Test" 
... 
    > 
    <UserControl.Resources> 
     <Converters:BoolToVisibilityConverter x:Key="boolVisibilityConverter" /> 
    </UserControl.Resources> 
    <Grid> 
     <local:ImageButton Image="/SilverlightApplication11;component/Themes/hand.png" Command="{Binding ButtonCommand}" Visibility="{Binding FallbackValue=Visible, Path=ToolIsAvailable, Converter={StaticResource boolVisibilityConverter} }"/> 
    </Grid> 
</UserControl> 

и код позади

public Test(TestCommandViewModel vm) 
    { 
     InitializeComponent(); 

     this.Loaded += (o, e) => this.DataContext = vm; 
    }