Xaml中的布尔到光标转换器

时间:2018-01-16 10:37:04

标签: c# wpf xaml

我编写了一个继承自IValueConverter的转换器类。当我使用此转换器将控件的光标绑定到CheckBox或ToggleButton的Ischecked属性时,没有任何反应。这是我的BooleanToCursorConverter课程:

using System;
using System.Windows.Data;
using System.Windows.Input;

namespace Machine_Vision
{
    [ValueConversion(typeof(bool?), typeof(CursorType))]
    public class BooleanToCursorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if ((bool?)value==true)
            {
                return CursorType.Cross;
            }
            else
            {
                return CursorType.Arrow;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }
}

这是我的XAML代码(简化):
  

<Window x:Class="Machine_Vision.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Machine_Vision"
        mc:Ignorable="d"
        Title="MainWindow"
        Height="650"
        Width="1300"
        WindowStartupLocation="CenterScreen"
        WindowState="Maximized"
        Closing="Window_Closing">
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="B2V" />
        <local:BooleanToCursorConverter x:Key="C2V" />
    </Window.Resources>
    <Grid>
        <Image x:Name="Original_View"
               Cursor="{Binding IsChecked, Converter={StaticResource C2V}, ElementName=DrawPoints}" />
        <ToggleButton x:Name="DrawPoints"
                      Content="Draw Points"
                      Margin="5" />
     <Grid/>

1 个答案:

答案 0 :(得分:1)

您从转换器返回了错误类型的值。 Cursor属性只能设置为System.Windows.Input.Cursor

[ValueConversion(typeof(bool?), typeof(Cursor))]
public class BooleanToCursorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((bool?)value == true)
        {
            return Cursors.Cross;
        }
        else
        {
            return Cursors.Arrow;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}