[英]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.