zoukankan      html  css  js  c++  java
  • 2019-9-18-WPF-笔刷绑定不上可能的原因

    title author date CreateTime categories
    WPF 笔刷绑定不上可能的原因
    lindexi
    2019-09-18 09:46:14 +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

  • 相关阅读:
    javascript时间戳和日期字符串相互转换
    jquery两稳定版本比较~~
    原生的强大DOM选择器querySelector
    分享一个自定义的 console 类,让你不再纠结JS中的调试代码的兼容
    基于Mesos运行Spark
    chrome插件 postman 可以调用restful服务
    cassandra优秀博客集
    Cassandra监控
    Cassandra
    SecureCRT中文显示乱码的解决方法
  • 原文地址:https://www.cnblogs.com/lindexi/p/12085861.html
Copyright © 2011-2022 走看看