【问题标题】:IValueConverter returning as object not value that is expectedIValueConverter 作为对象返回而不是预期的值
【发布时间】:2020-04-09 16:28:12
【问题描述】:

我正在尝试将标签(或任何东西)上的字符串转换为另一个字符串。这是用于图标字体的。

转换器

  [ValueConversion(typeof(string), typeof(string))]
    public class StringToIconConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string property = ((string)value).ToLower();
            switch (property)
            {
                case "maximize": return @"\e901";
                default return property;
            }
        }
         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }

      ...

   }

然后我已将其添加到需要它的页面中

        <Helpers:StringToIconConverter x:Key="Icon" />

我就是这样设置的

<Button Style="{StaticResource NavButton}"
                        Tag="Document"
                        Command="{Binding GotoDataMatrixEnterCommand}">
    <Button.Content>
        <Label Content="{Binding Source={RelativeSource Self}, 
                         Path=Tag,
                         Converter={StaticResource Icon}, 
                         UpdateSourceTrigger=LostFocus}" 
                         Tag="Document" />
    </Button.Content>
</Button>

我得到的是

Windows.System.Control.Label 代替它。我是否没有正确转换它,我不太确定为什么它没有替换正确的信息。我已经尝试了一些东西,并在网上阅读,尽管我现在被困住了。另外,当我尝试调试时它不起作用(它永远不会遇到断点)

【问题讨论】:

  • 您的错误是 {RelativeSource} 扩展应该与 Binding 的 RelativeSource 属性一起使用,而不仅仅是 Source:{Binding RelativeSource={RelativeSource Self}, Path=...}
  • 好吧,我去看看试试看,我相信我试过了,但可能没有,或者当时有什么问题

标签: c# wpf ivalueconverter


【解决方案1】:

问题在于 Label.Content 上的绑定。您应该使用 RelativeSource,而不是 Source。

应该是:

RelativeSource={RelativeSource Mode=Self}

此外,StringToIconConverterswitch 语句中存在语法错误:default return property; 应该是 default: return property;(您缺少冒号)。

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 2018-11-03
    • 2015-04-09
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 2014-06-18
    • 2013-02-23
    • 1970-01-01
    相关资源
    最近更新 更多