WPF触发器/绑定无法正常工作

hum*_*ory 2 c# data-binding wpf xaml datatrigger

我正在尝试设置一个TextBox子类,它将根据一些不同的东西改变它的样式,我遇到了两个问题.第一个触发器,即VisualBrush触发器,可以正确触发,但不会在String 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>
Run Code Online (Sandbox Code Playgroud)

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!";
    }

}
Run Code Online (Sandbox Code Playgroud)

这是StackOverflow它的代码.也没有工作,但没有异常是:

public string myName = "Rainbows!";
Run Code Online (Sandbox Code Playgroud)

Joh*_*ner 5

 public string myName    
 {        
     get { return myName; }        
     set {}    
 }
Run Code Online (Sandbox Code Playgroud)

该属性吸气剂被返回本身,因此堆栈溢出.

并且安装员什么都不做,因此"没有工作"

可能想要:

 private string myName; // lower case!
 public string MyName    // upper case!
 {        
     get { return myName; }        
     set { myName = value; }    
 }
Run Code Online (Sandbox Code Playgroud)

甚至

 public string myName { get; set; }
Run Code Online (Sandbox Code Playgroud)

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

  • 另请注意,OnNotifyPropertyChanged的实现不遵循在测试null和raise之前将事件分配给本地临时的惯用做法.在多线程或重入场景(您甚至不知道)中,您的代码可能会爆炸.相反,OnNotifyPropertyChanged应该是这样的:`var event = this.PropertyChanged; if(event!= null)event(this,args);`这消除了测试null和执行事件委托之间存在的竞争条件. (2认同)