繁体   English   中英

在后面的代码中更改应用程序资源属性

[英]Change Application Resource Property in Code Behind

我在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>

(我只是给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是否返回不是null的东西,依此类推(我认为您可以处理它;))

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM