• 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

  • 相关阅读:
    域控制器的常规卸载,Active Directory系列之十三
    理解域信任关系,Active Directory系列之十六
    什么是站点,Active Directory系列之十一
    域控制器的强制卸载,Active Directory系列之十四
    详解操作主机角色,Active Directory系列之九
    【转】MapControl和PageLayoutControl的同步
    AE的一些接口小记
    【转】centos linux 上flv/swf视频服务器架设
    lnmp配置超精简免费flv流媒体服务器笔记
    Flash game 遊戲修改 Cheat Engine 5.4 使用教學
  • 原文地址:https://www.cnblogs.com/lindexi/p/12085861.html
Copyright © 2020-2023  润新知