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

本文关键字:绑定 属性 用户 控件 检测 | 更新日期: 2023-09-27 18:12:57

我正在制作一个Windows Store应用程序,其中我有一个用户控件作为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>

用户控制类:(imagpage . example .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元素ON或OFF取决于它的数据绑定。

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

TextBlock没有DataContext来查找DependencyProperty。如果你给你的Grid一个名称在imagpage .xaml:

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

然后您可以在imagpage . example .cs:

ImagePage构造函数中设置它的DataContext。
    public ImagePage()
    {
        InitializeComponent();
        MyGrid.DataContext = this;
    }

告诉Grid(及其后代)在ImagePage类上查找依赖属性。这样,Dependency属性就应该得到正确的绑定。另一个问题,虽然,是你告诉DependencyProperty,它是在ImagePagetypeof(ImagePage)上,但然后将其转换为StackPanel,这将每次失败:

    StackPanel stackPanel = (StackPanel)d; // Throws System.InvalidCastException

你可以通过给StackPanel一个名字并直接在你的。cs文件中引用它来修复这个问题。