wpf - 超链接不能与相关命令一起正常工作

标签 wpf xaml data-binding hyperlink

我在 Grid 中有 Hyperlink。我将命令绑定(bind)到启用/禁用它的超链接。然后我使用命令禁用它。然后在其父级 (Grid) 上设置 IsEnabled=False 属性。之后,我使用我的命令启用我的超链接并启用网格,但超链接没有激活!

这是示例:

Command testCommand = new Command();

public MainWindow() {
  InitializeComponent();
  hl.Command = testCommand;
}

private void Start(object sender, RoutedEventArgs e) {

  //Disable Hyperlink
  testCommand.Enabled = false;
  //Disable Grid
  grid.IsEnabled = false;
  //Enable Hyperlink
  testCommand.Enabled = true;
  //Enable Grid
  grid.IsEnabled = true;
  //hl.IsEnabled = true; //if uncomment this all will be work
}

XAML:

<Window x:Class="WpfApplication25.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="172"
        Width="165">
  <StackPanel>
    <Grid x:Name="grid">
      <TextBlock>
        <Hyperlink x:Name="hl">Test</Hyperlink>
      </TextBlock>
    </Grid>
    <Button Content="Start"
            Name="button1"
            Click="Start" />
  </StackPanel>
</Window>

并注册一个 ICommand:

public class Command : ICommand {
  private bool enabled;
  public bool Enabled {
    get {
      return enabled;
    }
    set {
      enabled = value;
      if (CanExecuteChanged != null)
        CanExecuteChanged(this, EventArgs.Empty);
    }
  }
  public bool CanExecute(object parameter) {
    return Enabled;
  }
  public event EventHandler CanExecuteChanged;
  public void Execute(object parameter) { }
}

更新:

如果将 Hyperlink 替换为 Button,即使其父项被禁用 (grid.IsEnabled = false),它也会被启用。

最佳答案

我知道了 这就是你所缺少的

 public class Command : ICommand
    {
        private bool enabled;
        public bool Enabled
        {
            get
            {
                return enabled;
            }
            set
            {
                enabled = value;
                //if (CanExecuteChanged != null)
                //    CanExecuteChanged(this, EventArgs.Empty);
            }
        }

        public bool CanExecute(object parameter)
        {
            return Enabled;
        }
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter) { }
    }

CanExecuteChanged 将命令订阅委托(delegate)给 CommandManager

关于wpf - 超链接不能与相关命令一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13071931/

相关文章:

c# - MVVM Light RelayCommand 参数

c# - 控件如何确定使用哪个 DataContext?

android - 如何使用 ToggleButton 执行双向数据绑定(bind)?

wpf - 在标签上显示标准文本?

android - 没有 View ID 时的 onSaveInstanceState Activity

javascript - 没有 $scope 的 AngularFire 3 路绑定(bind)

c# - DataGrid 设置只读并允许滚动?

c# - WPF slider 控件 (NullReferenceException)

c# - 将图像添加到 wpf 中的标签?

xaml - Xamarin.Forms 工具栏项目图标大小