2019-11-29-WPF-笔刷绑定不上可能的原因

title author date CreateTime categories
WPF 笔刷绑定不上可能的原因
lindexi
2019-11-29 08:46:22 +0800
2019-9-18 9:2:33 +0800
WPF

在 WPF 中如背景色等都是使用笔刷,在使用绑定的时候可能绑定不上,本文告诉大家绑定不上可能的原因和调试方法

有小伙伴问我为什么他的背景绑定不上,他的代码如下

    <Window.Resources>
        <local:StateToColorConverter x:Key="StateToColorConverter"></local:StateToColorConverter>
    </Window.Resources>
    <Grid >
        <Grid Background="{Binding Path=Width,Converter={StaticResource StateToColorConverter}}"></Grid>
    </Grid>

其中后台代码如下

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
        }
    }

    public class StateToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            switch (value)
            {
               
                default:
                    return Brushes.Transparent.Color;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

这是简化的版本

原因是在小伙伴在转换器里面绑定的返回值是 Color 而 Background 的需要的值是 Brush 所以绑定不上

修复方法是不返回 Color 应该返回 Brush 就可以

调试 XAML 绑定可以通过在 VisualStudio 的选项开启输出绑定信息

在工具 选项 调试 输出窗口 可以看到绑定的输出,将这一项设置为详细就可以输出很多调试信息,如上面代码将会输出绑定返回值

System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=Width; DataItem=null; target element is 'Grid' (Name=''); target property is 'Background' (type 'Brush')

翻译一下

System.Windows.Data Information: 10 : 无法接受绑定的返回值,同时没有设置绑定失败使用的值;将使用默认值代替。绑定表达式是 Path=Width 数据项是没有,绑定的元素是 Grid 绑定的属性是 Background 这个属性的类型是 Brush 类型

如果不想每次都设置 VisualStudio 可以使用 WPF 如何调试 binding

原文地址:https://www.cnblogs.com/lindexi/p/12085412.html