在正确的字母上更改文本框颜色?

时间:2016-05-07 15:44:41

标签: c# wpf xaml

我正在使用WPF创建填字游戏。我的所有文本框都是红色的,但是当某个文本框包含正确的单词时,我希望它们更改为绿色。

请问有人帮忙吗?

2 个答案:

答案 0 :(得分:1)

Bind TextBox Background stringWord属性,我们将其命名为ValueConverter

然后使用WordColor转换为WordColorConverter,我们将其命名为IValueConverter(这是一个实现Window的类)

您的xaml看起来像这样,假设它位于WordColorConverter,您将local放在<Window.Resources> <local:WordColorConverter x:Key="WordColorConverter"/> </Window.Resources> <Grid> <TextBox Text="{Binding Word}", Background="{Binding Word, Converter={StaticResource WordColorConverter}}"/><</ </Grid> 命名空间中

class WordColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string word = (string)value;
            if (word.Equals("correct word"))
            {
                return new SolidColorBrush(Colors.Green);
            }
            else
            {
                return new SolidColorBrush(Colors.Red);
            }
        }

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

你的WordColorConverter类看起来像这样......

MultiBinding

编辑:您可以尝试<TextBox Text="{Binding InputWord, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"> <TextBox.Background> <MultiBinding Converter="{StaticResource WordColorConverter}"> <Binding Path="InputWord" /> <Binding Path="CorrectWord" /> </MultiBinding> </TextBox.Background> </TextBox>

   public class WordColorConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            string inputWord = (string)values[0];
            string correctWord = (string)values[1];
            if (inputWord.Equals(correctWord))
            {
                return new SolidColorBrush(Colors.Green);
            }
            else
            {
                return new SolidColorBrush(Colors.Red);
            }
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {

            throw new NotImplementedException();
        }
    }


/// <reference path=".vscode/node.d.ts" />

答案 1 :(得分:0)

你可以试试这样的事情;

    <TextBox>
        <TextBox.Style>
            <Style TargetType="{x:Type TextBox}">
                <Setter Property="Foreground" Value="Red"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=aCertainTextBox, Path=Text}" Value="CorrectWord">
                        <Setter Property="Foreground" Value="Green" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>

这会查看&#34; aCertainTextbox&#34;的值,如果文本框文本是&#34; CorrectWord&#34;它将文本的颜色设置为绿色,任何其他单词应该是红色。显然,您需要更改&#34; ACertainTextBox&#34;的名称。和&#34; CorrectWord&#34;你想要的实际单词是&#34; aCertainTextbox&#34;

相关问题