WPF为什么没有初始绑定触发器设置器?

时间:2014-11-04 03:10:23

标签: c# wpf data-binding

我有以下Button

<Button x:Class="MvvmAttempt.UpdownButton"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:MvvmAttempt"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300" HorizontalContentAlignment="Stretch">
    <Button.Resources>
        <ResourceDictionary Source="resources/Styles.xaml"/>
    </Button.Resources>

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="3*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <Viewbox Stretch="Uniform" Grid.Column="0">
            <TextBlock x:Name="numCopyTB" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=Text}"/>
            <!--<TextBlock x:Name="numCopyTB"/>-->   <-- doesn't work propery
        </Viewbox>
        <Viewbox Grid.Column="1">
            <TextBlock Style="{StaticResource updownBlock}"/>
        </Viewbox>

    </Grid>
</Button>

其代码隐藏

public partial class UpdownButton : Button 
{

    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(UpdownButton));


    public UpdownButton()
    {
        InitializeComponent();
    }

    public string Text
    {
        get { return GetValue(TextProperty) as string; }
        set { SetValue(TextProperty, value);
              //numCopyTB.Text = Text; <-- doesn't work properly
        }
    }
}

正如您所看到的,我已将Text属性添加到UpdownButton,该属性来自Button。名为TextBlock的{​​{1}}的{​​{1}}属性与numCopyTB的属性绑定,因此Text的{​​{1}}显示在UpdownButton上并且也正确更新。

但是,在XAML中注释掉绑定,并在代码隐藏中设置Text&#39; UpdownButton并不能正常工作:最初没有显示任何文本;只有后续调用TextBlock才有效。最初的numCopyTB属性绑定如下:

Text

因此,原始绑定似乎不会在后面的代码中触发myUpdownButton.Text="new text";。为什么不呢?

0 个答案:

没有答案