2012-05-30 59 views
0

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

    } 

有关如何做到这一点的任何想法?非常感谢您的帮助和意见。

回答

1

你可以尝试像(使用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作为附加资源),否则甚至根本不会使用模板,如果您想修改其中的属性:可能导致应用程序崩溃,因为空指针异常,如果管理不好)

+0

谢谢你的答案。毕竟我最终没有使用模板。我觉得最终不是最合适的模板使用方式,并没有最好地满足我的应用程序的需求。但也许这个答案会帮助别人。再次感谢。 – QuittersNL

相关问题