c# - WPF 触发器/绑定(bind)不起作用

标签 c# wpf xaml data-binding datatrigger

我正在尝试设置一个 TextBox 子类,该子类将根据一些不同的事情更改其样式,但我遇到了两个问题。第一个触发器(VisualBrush 触发器)正确触发,但不会在字符串 myName 中写入文本。我尝试将 myName 设置为属性,但由于某种原因,set 方法抛出 StackOverFlowException。

第二个问题是 DataTrigger,即使 isRequired 设置为 false,它也不会被触发。

这一切都在继承 TextBox 的自定义控件内。

这是我的 XAML:

    <TextBox.Style>
    <Style TargetType="TextBox">
        <Style.Triggers>
            <Trigger Property="Text" Value="">
                <Setter Property="Background">
                    <Setter.Value>
                        <VisualBrush Stretch="None">
                            <VisualBrush.Visual>
                                <TextBlock Foreground="Gray" FontSize="24">
                                        <TextBlock.Text>
                                            <Binding Path="myName" RelativeSource="{RelativeSource Self}" />
                                        </TextBlock.Text>
                                </TextBlock>
                            </VisualBrush.Visual>
                        </VisualBrush>
                    </Setter.Value>
                </Setter>
            </Trigger>
            <DataTrigger Binding="{Binding Path=isRequired, Source={RelativeSource Self}}" Value="False">
                <Setter Property="Text" Value="100" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TextBox.Style>

CS:

    public partial class SuperTB : TextBox
{
    public String myName
    {
        get { return myName; }
        set {}
    }

    DependencyProperty isRequiredProperty = DependencyProperty.Register("isRequired", typeof(Boolean), typeof(SuperTB));

    public Boolean isRequired
    {
        get { return (Boolean)GetValue(isRequiredProperty); }
        set { SetValue(isRequiredProperty, value); }
    }

    public SuperTB()
    {
        InitializeComponent();
        myName = "Unicorns!";
    }

}

这是 StackOverflows 的代码。也无法工作但没有异常(exception)的是:

public string myName = "Rainbows!";

最佳答案

 public string myName    
 {        
     get { return myName; }        
     set {}    
 }

该属性 getter 返回自身,因此堆栈溢出。

并且 setter 什么也没做,因此“无法工作”

可能想要:

 private string myName; // lower case!
 public string MyName    // upper case!
 {        
     get { return myName; }        
     set { myName = value; }    
 }

甚至

 public string myName { get; set; }

即使如此,这仍然不会像您期望的那样工作,因为那里没有任何东西触发任何属性更改通知,所以没有人会注意到 myName 发生了变化。

关于c# - WPF 触发器/绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6512425/

相关文章:

c# - 将 RadioButtons 绑定(bind)到单个属性?

c# - 转换 Func<> 类型

c# - 为什么断点条件执行失败?

wpf - 我的 WPF DataGrid 中的 ComboBox 不会显示任何项目

wpf - Cefsharp 清除 wpf 中的缓存、cookie 和浏览器数据

debugging - 如何跟踪 XAML 加载期间发生的情况?

c# - 如何使用 DataAnnotations 使用多个文件扩展名?

c++ - 在 WPF 应用程序中托管 win32 窗口?

c# - 在 WPF 的 ContentControl 中托管 ViewModel

wpf - 如何像气泡一样设置WPF工具提示的样式?