简体   繁体   English

使用 XAML 中的转换器更改背景颜色

[英]Changing background color with a converter in XAML

TextBlock background color not changing. TextBlock背景颜色不变。

I've bound my data to a TextBlock which updates with INotifyPropertyChanged , and the converter does fire.我已将我的数据绑定到使用INotifyPropertyChanged更新的TextBlock ,并且转换器确实会触发。

public class Oddsindicator : IMultiValueConverter
{

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string myPrice = "0";
        string tradePrice = "0";

        var colorRed = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#FFB0E0E6");
        var colorWhite = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("White");

        var unchanged = new SolidColorBrush(colorRed);
        var changed = new SolidColorBrush(colorGreen);

        if (values[0] != DependencyProperty.UnsetValue)
        {
            myPrice = values[0].ToString();
            tradePrice = values[1].ToString();
        }

        if (myPrice == tradePrice)
        {
            return unchanged;
        }
        else
        {
            return changed;
        }
    }
}

XAML: XAML:

<Window.Resources>

    <local:Oddsindicator x:Key="Oddsindicator" >

    </local:Oddsindicator>

</Window.Resources>

<TextBlock Text="{Binding BackPrice, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"  TextAlignment="Center" Margin="1"  Grid.Row="4" Grid.Column="2" />
<TextBlock>
    <TextBlock.Background>
        <MultiBinding Converter="{StaticResource Oddsindicator}">

            <Binding Path="BackPrice"/>
            <Binding Path="Lasttradedprice" />

        </MultiBinding>
    </TextBlock.background>
</TextBlock>

I've used break points at the return and they both fire.我在返回时使用了断点,它们都开火了。 My bound value updates perfectly.我的绑定值完美更新。 The converters comparing the values and giving the correct results, just not updating the TextBlock .转换器比较值并给出正确的结果,只是不更新TextBlock

(This should in fact be a comment but I need the formatting features of an answer) (这实际上应该是评论,但我需要答案的格式化功能)

You have two TextBlocks.你有两个文本块。 The second (for which you set the background) has no Text and is probably of 0 size.第二个(您为其设置背景)没有文本,可能大小为 0。 Try putting the TextBlock.Background in the first TextBlock:尝试将TextBlock.Background放在第一个 TextBlock 中:

<TextBlock Text="{Binding BackPrice, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"  TextAlignment="Center" Margin="1"  Grid.Row="4" Grid.Column="2" >
    <TextBlock.Background>
        <MultiBinding Converter="{StaticResource Oddsindicator}">
            <Binding Path="BackPrice"/>
            <Binding Path="Lasttradedprice" />
        </MultiBinding>
    </TextBlock.Background>
</TextBlock>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM