更改代码隐藏中的应用程序资源属性

本文关键字:应用程序 资源 属性 代码 隐藏 | 更新日期: 2023-09-27 18:35:42

我在 Silverlight (Form.xaml) 中有一个用户控件,它使用标签来显示数据。 目前,我有这些标签的前景色和可见性,由 app.xaml 中的模板控制,如下所示:

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
             x:Class="TestSilverlight.App"
             >
    <Application.Resources>
        <ControlTemplate x:Key="DataLabel" x:Name="DataLabel" TargetType="sdk:Label">
            <sdk:Label Visibility="Visible" Foreground="White" Content="{TemplateBinding Content}"></sdk:Label>
        </ControlTemplate>
    </Application.Resources>
</Application>

下面是 Form.xaml 中标签的 xaml:

<sdk:Label Template="{StaticResource DataLabel}" HorizontalAlignment="Left" Margin="140,53,0,0" VerticalAlignment="Top" Content="Ground" FontSize="13.333" Width="138"/>

当我点击 Form.xaml 的编辑按钮时,我想隐藏这些标签。 但是,我无法弄清楚如何更改此模板的隐藏代码中的可见性属性。

    private void EditButton_Click(object sender, RoutedEventArgs e)
    {
        // Place code to alter template properties here...
    }

关于如何做到这一点的任何想法? 非常感谢您的帮助和投入。

更改代码隐藏中的应用程序资源属性

你可以尝试类似的东西(使用 WPF 工作):

    <ControlTemplate x:Key="DataLabel" x:Name="DataLabel" TargetType="sdk:Label">
        <sdk:Label x:Name="myLabelTemplate" Visibility="Visible" Foreground="White" Content="{TemplateBinding Content}"></sdk:Label>
    </ControlTemplate>

(我只是给控件模板中的标签命名)

<sdk:Label x:Name="myLabel" Template="{StaticResource DataLabel}" HorizontalAlignment="Left" Margin="140,53,0,0" VerticalAlignment="Top" Content="Ground" FontSize="13.333" Width="138"/>

(我只是给 xaml 中的标签起了一个名字)

        var res = (FindResource("DataLabel") as ControlTemplate).FindName("myLabelTemplate", myLabel);
        if (res != null && res is FrameworkElement)
            (res as FrameworkElement).Visibility = Visibility.Hidden;

我没有检查 FindResource 是否返回不为空的内容,等等(我认为您可以;)处理它)

但是,如果我是你,我不会使用应用程序资源来放置用户控件的特定资源(我会在 userControl 的 xaml 中使用模板(作为附加资源),或者如果你想修改其中的属性,甚至根本不会使用模板:如果管理不当,可能会导致应用程序崩溃,因为空指针异常)