【问题标题】:WPF the textblock background color can't binding variableWPF文本块背景颜色不能绑定变量
【发布时间】:2019-09-19 11:09:08
【问题描述】:

对不起。我是菜鸟。我想单击按钮更改文本块的背景颜色。变量的值可以改变,但背景的颜色没有改变。有我的代码。请帮助我。

视觉工作室 2017

enter image description here

WPF

文本块

<TextBlock Width="75" Height="75" HorizontalAlignment="Center" Margin="205,187,626,468" FontSize="48">
        <TextBlock.Style>
            <Style TargetType="TextBlock">

                <Setter Property="Text" Value="1" />
                <Setter Property="Background" Value="Red" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=TestView,Mode=TwoWay}" Value="True">
                        <Setter Property="Text" Value="1" />
                        <Setter Property="Background" Value="Green" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>

和按钮

<Button Margin="202,596,564,0" VerticalAlignment="Top" Width="134" Click="buttonClick"> </Button>

Xaml.cs

private bool testView = true;
    public bool TestView
    {
        get { return testView; }
        set { testView = value; }
    }

    private void buttonClick(object sender, RoutedEventArgs e)
    {
        TestView = false;
    }

我希望当 testView == true 时,textblock 的背景颜色为绿色,而 testView == false 时,textblock 的背景颜色为红色。 并且文本在 TextBlock 的中间

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    窗口(视图)未更新的原因是您需要通知它发生更改。要在 WPF 中执行此操作,您必须实现 INotifyPropertyChanged 接口,并相应地设置 DataContext。通常,这应该使用 MVVM 设计模式来完成,但为了回答您的问题,以下是如何使用您当前的设置来完成:

      public partial class Window1 : Window, INotifyPropertyChanged
        {
            private bool testView = true;
            public bool TestView
            {
                get { return testView; }
                set 
                { 
                    if (testView != value)
                    {
                        testView = value;
                        OnPropertyChanged("TestView");
                    }
                }
            }
    
            public Window1()
            {
                InitializeComponent();
                DataContext = this;
            }
    
            private void buttonClick(object sender, RoutedEventArgs e)
            {
                TestView = false;
            }
    
            #region INotify
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
            #endregion INotify
        }
    

    【讨论】:

    • @xeroxion 你能接受这个作为答案吗=]
    • 不好意思,最近比较忙,马上测试
    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 2011-05-07
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多