首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF: ValueConverter (IValueConverter)不工作

WPF: ValueConverter (IValueConverter)不工作
EN

Stack Overflow用户
提问于 2016-10-07 13:11:53
回答 2查看 2.2K关注 0票数 1

我有一个Window类,其中有几个TextBlock元素,它们应该通过Binding属性值接收Background颜色。第一个“转换器绑定”工作良好,并完成一切期望。今天,我尝试用另一个用于它的Converter实现另一个“转换器绑定”,但它不起作用:

(我省略了ConvertBack方法,因为它们在这里是不必要的):

代码语言:javascript
复制
namespace InsightTool.Gui.Helper {
    [ValueConversion(typeof(double), typeof(Brush))]
    public class AverageExecutionTimeToColorConverter : IValueConverter {
        public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            double val;
            double.TryParse(value.ToString(), out val);

            if (val >= 10000) {
                return Brushes.Red;
            } else if (val >= 5000) {
                return Brushes.Orange;
            } else {
                return Brushes.Green;
            }
        }
    }

    [ValueConversion(typeof(int), typeof(Brush))]
    public class ThreadsAvailableCountToColorConverter : IValueConverter {
        public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            int val;
            int.TryParse(value.ToString(), out val);

            if (val < 100) {
                return Brushes.Red;
            } else if (val < 200) {
                return Brushes.Orange;
            } else if (val < 500) {
                return Brushes.Yellow;
            } else {
                return Brushes.Green;
            }
        }
    }
}

Window类中,我使用了两个转换,如下所示:

代码语言:javascript
复制
<Window ...
    x:Name="Main"
    xmlns:Base="clr-namespace:InsightTool.Gui.Helper">
    <Window.Resources>
        <Base:ThreadsAvailableCountToColorConverter x:Key="ThreadsAvailableCntConverter"/>
        <Base:AverageExecutionTimeToColorConverter x:Key="AvgExecutionTimeConverter"/>     
    </Window.Resources>

    <!-- This one works fine-->
    <TextBlock Width="10" Height="10" VerticalAlignment="Center" Background="{Binding ExecutionTimeAverage, Converter={StaticResource AvgExecutionTimeConverter}, ElementName=UCExecutionTimes}"/>

    <!-- This one does not work-->
    <TextBlock Width="10" Height="10" VerticalAlignment="Center" Background="{Binding ThreadsAvailableCount, Converter={StaticResource ThreadsAvailableCntConverter}, ElementName=Main}"/>
</Window>

DependencyProperties声明

代码语言:javascript
复制
public partial class UserControlExecutionTimes : UserControl {
    public static readonly DependencyProperty ExecutionTimeAverageProperty =
             DependencyProperty.Register("ExecutionTimeAverage", typeof(double), typeof(MainWindow), new FrameworkPropertyMetadata(double));

    public double ExecutionTimeAverage {
        get { return (double)GetValue(ExecutionTimeAverageProperty); }
        set { SetValue(ExecutionTimeAverageProperty, value); }
    }
}


public partial class MainWindow : Window {
    public static readonly DependencyProperty ThreadsAvailableCountProperty = DependencyProperty.Register("ThreadsAvailableCount", typeof(int),
         typeof(MainWindow), new FrameworkPropertyMetadata(int));

    public int ThreadsAvailableCount {
        get { return (int)GetValue(ThreadsAvailableCountProperty); }
        set { SetValue(ThreadsAvailableCountProperty, value); }
    }
}

两个DependencyProperties的设置都是正确的,它们的值都显示在GUI中。我在这里错过了什么?

编辑:

我还测试了以下内容:

代码语言:javascript
复制
<Window>
    <!-- This one works fine-->
    <TextBlock Width="10" Height="10" VerticalAlignment="Center" Background="{Binding ThreadsAvailableCount, Converter={StaticResource AvgExecutionTimeConverter}, ElementName=Main}"/>

    <!-- This one does not work-->
    <TextBlock Width="10" Height="10" VerticalAlignment="Center" Background="{Binding ThreadsAvailableCount, Converter={StaticResource ThreadsAvailableCntConverter}, ElementName=Main}"/>
</Window>

似乎Binding使用“新”转换器的返回值存在问题,但我不知道原因。

EDIT2

我使用Snoop检查绑定,结果如下:

工作转换器绑定的background属性如下所示:

但是,非工作转换器绑定的background属性如下所示:

另一个证明ThreadsAvailableCount设置正确的证据(绑定到Textblock):

显示ThreadsAvailableCountToColorConverter的返回值似乎越来越多地是一个错误。这是因为在调试模式下,它停止在Convert方法的ThreadsAvailableCountToColorConverter中的一个断点。它甚至在return方法中成功地达到Convert方法。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-15 09:40:06

阿!终于解决了这个问题。我也有同样的问题。使用TextBlock,使用IValueConverter转换为Brush

绑定工作正常,没有错误或输出。值进入IValueConverter代码,我可以直接调试到返回语句.没什么!

您做的一切都是正确的,但是您自动导入了错误的Brushes。我一直和WPF一起做。

替换using语句:

代码语言:javascript
复制
using System.Drawing

通过以下方式:

代码语言:javascript
复制
using System.Windows.Media

WPF使用System.Windows.Media.Brushes,但是很容易导入几乎相同的System.Drawing.Brushes而不需要注意。这一切看起来都很好,直到WPF掌握了它,并且无法实际使用它。但它“优雅地”失败了,因为它回到了默认的颜色上。

票数 3
EN

Stack Overflow用户

发布于 2016-10-07 16:03:24

我认为可能存在多个问题,请查看绑定表达式错误的“输出窗口”。1)确保文本框在单独的区域内呈现,且不重叠。2)使用相对路径访问控件,并在绑定表达式中使用它的属性

你的转换器看起来很好。

以下是我的xaml

代码语言:javascript
复制
<Window x:Class="StackOverflowBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:stackOverflowBinding="clr-namespace:StackOverflowBinding"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <stackOverflowBinding:ThreadsAvailableCountToColorConverter x:Key="ThreadsAvailableCntConverter"/>
        <stackOverflowBinding:AverageExecutionTimeToColorConverter x:Key="AvgExecutionTimeConverter"/>
    </Window.Resources>
    <Grid>
        <!--<DatePicker 
        x:Name="newtally" 
        Text="{Binding CustomerLastTally,Mode=TwoWay}"  
        Margin="0 0 0 0" 
        />-->
        <!-- This one works fine-->
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Grid.Column="0" Width="30" Height="30" Text="Break"/>
        <TextBlock Grid.Row="1" Grid.Column="0"  Width="30" Height="30" VerticalAlignment="Center"  Text="Break" Background="{Binding ExecutionTimeAverage, Converter={StaticResource AvgExecutionTimeConverter}, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>

        <!-- This one does not work-->
        <TextBlock Grid.Row="2" Grid.Column="0"  Width="30" Height="30" VerticalAlignment="Center" Text="Break" Background ="{Binding ThreadsAvailableCount, Converter={StaticResource ThreadsAvailableCntConverter}, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
    </Grid>

</Window>

下面是我的代码

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace StackOverflowBinding
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        // Dependency Property
        public static readonly DependencyProperty ExecutionTimeAverageProperty =
             DependencyProperty.Register("ExecutionTimeAverage", typeof(DateTime),
             typeof(MainWindow), new FrameworkPropertyMetadata(DateTime.Now));

        // .NET Property wrapper
        public DateTime ExecutionTimeAverage
        {
            get { return (DateTime)GetValue(ExecutionTimeAverageProperty); }
            set { SetValue(ExecutionTimeAverageProperty, value); }
        }

        // Dependency Property
        public static readonly DependencyProperty ThreadsAvailableCountProperty =
             DependencyProperty.Register("ThreadsAvailableCount", typeof(int),
             typeof(MainWindow), new FrameworkPropertyMetadata(40));

        // .NET Property wrapper
        public int ThreadsAvailableCount
        {
            get { return (int)GetValue(ThreadsAvailableCountProperty); }
            set { SetValue(ThreadsAvailableCountProperty, value); }
        }
    }
}

以下是我的转换器

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media;

namespace StackOverflowBinding
{

    [ValueConversion(typeof(double), typeof(Brush))]
    public class AverageExecutionTimeToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double val;
            double.TryParse(value.ToString(), out val);

            if (val >= 10000)
            {
                return Brushes.Red;
            }
            else if (val >= 5000)
            {
                return Brushes.Orange;
            }
            else
            {
                return Brushes.Green;
            }
        }

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

    [ValueConversion(typeof(int), typeof(Brush))]
    public class ThreadsAvailableCountToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            int val;
            int.TryParse(value.ToString(), out val);

            if (val < 100)
            {
                return Brushes.Red;
            }
            else if (val < 200)
            {
                return Brushes.Orange;
            }
            else if (val < 500)
            {
                return Brushes.Yellow;
            }
            else
            {
                return Brushes.Green;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39918156

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档