【问题标题】:Binding Click action to custom xaml component将单击操作绑定到自定义 xaml 组件
【发布时间】:2016-10-16 20:57:58
【问题描述】:

我在 XAML 中有以下自定义控件:

<Button x:Name="button" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Center" Width="200">
        <StackPanel Orientation="Horizontal" Width="170">
            <TextBlock Text="&#xE188;" FontFamily="Segoe UI Symbol" Visibility="{Binding isFolder, Converter={StaticResource BooleanToVisibilityConverter}}"/>
            <TextBlock Text="&#xE113;" FontFamily="Segoe UI Symbol" Foreground="Gold" Visibility="{Binding isFolder, Converter={StaticResource InverseBooleanToVisibilityConverter}}"/>
            <TextBlock Text="{Binding title}" Margin="5,0" Foreground="Black"/>
        </StackPanel>

我想在 isFolder 上绑定点击动作。所以我创建了一个 xaml 页面,并在后面的代码中添加了如下控件:

        MyControl item = new MyControl();
        item.DataContext = context;
        // item.click += context.isFolder ? folderAction : nonFolderAction

没有item.click。如何根据布尔值添加委托点击?

【问题讨论】:

    标签: c# xaml winrt-xaml


    【解决方案1】:

    你可以使用relaycommands来指定执行命令的条件。

    例如:(在你的情况下)

    在您的视图模型中:(执行此操作)

        private RelayCommand myCommandInViewModel;
    
        public RelayCommand MyCommandInViewModel
        {
            get { return myCommandInViewModel?? (myCommandInViewModel= new RelayCommand(myCommandInViewModelAction,()=> { return isFolder; })); }
        }
    

    myCommandInViewModelAction 有您的方法定义。

    以上是建议的做法。 否则,您可以通过另一种方式在 button.Click 事件中获取发送者的数据上下文并检查其中的 isFolder 属性。

    private void someClickEvent(object sender, RoutedEventArgs e)
        {
         var buttonDataContext = (sender as Button).DataContext;
         if(buttonDataContext.isFolder)
         {
           doSomeThing();
         }
         else
         {
         return;
        }
        }
    

    【讨论】:

      猜你喜欢
      • 2013-03-29
      • 2016-04-23
      • 1970-01-01
      • 2017-11-18
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 2011-04-05
      • 1970-01-01
      相关资源
      最近更新 更多