检测用户控件中的绑定属性已更改

时间:2014-07-15 16:37:39

标签: c# xaml binding user-controls propertychanged

我正在开发一个Windows应用商店应用,其中我有一个用户控件作为flipview内的数据模板。

用户控制:(ImagePage.xaml)

    <UserControl
    x:Name="userControl"
    x:Class="MWC_online.Classes.ImagePage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MWC_online.Classes"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="768"
    d:DesignWidth="1366">

    <Grid Background="#FFF0F0F0" Margin="4,0">
     ...
        <Image Source="{Binding Img}"  Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top" />
        <StackPanel x:Name="stackPanel" HorizontalAlignment="Left" Margin="984,83,0,0" Width="325">
            <Grid Background="{Binding Colour}">
                <TextBlock Margin="30,30,30,15" Text="{Binding TextContent1}" FontWeight="Light" TextWrapping="Wrap" Foreground="#FF00ABE8" FontSize="29" />
            </Grid>
            <Grid Background="{Binding Colour}">
                <TextBlock Margin="30,10,30,30" Text="{Binding TextContent2}" TextWrapping="Wrap" Foreground="#FF606060" FontSize="17" />
            </Grid>
        </StackPanel>
    </Grid>
</UserControl>

用户控件类:(ImagePage.xaml.cs)

private static void OnTitleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){
    StackPanel stackPanel = (StackPanel)d;
    stackPanel.Visibility = Visibility.Collapsed;
}

public string TextContent1
{
    get { return (string)GetValue(TextContent1Property); }
    set { SetValue(TextContent1Property, value); }
}
public static readonly DependencyProperty TextContent1Property =
    DependencyProperty.Register("TextContent1", typeof(string), typeof(ImagePage), new PropertyMetadata("", new PropertyChangedCallback(OnTextContent1Changed)));

private static void OnTextContent1Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    // what I want to do is if TextContent1 or TextContent2 has no value
    // turn the stackpanel visibility to collapsed
    StackPanel stackPanel = (StackPanel)d;
    stackPanel.Visibility = Visibility.Collapsed;
}

一切都工作正常除了OnTextContent1Changed没有解雇!所以我不知道这是否是正确的做事方式,但基本上我只想在用户控件中打开或关闭UI元素,具体取决于正在输入的数据绑定。

1 个答案:

答案 0 :(得分:0)

TextBlock没有DataContext来查找DependencyProperty。如果您在ImagePage.xaml中为Grid命名:

    <Grid Background="#FFF0F0F0" Margin="4,0" x:Name="MyGrid">

然后你可以在ImagePage.xaml.cs的ImagePage构造函数中设置它的DataContext:

    public ImagePage()
    {
        InitializeComponent();

        MyGrid.DataContext = this;
    }

告诉Grid(及其后代)在ImagePage类上查找依赖属性。有了这个,依赖属性应该正确绑定。但是,另一个问题是,您告诉DependencyProperty ImagePage typeof(ImagePage) StackPanel stackPanel = (StackPanel)d; // Throws System.InvalidCastException ,然后将其投放到StackPanel,每次都会失败:

{{1}}

您可以通过为StackPanel指定名称并直接在.cs文件中引用它来解决此问题。