如何在C#代码中将自定义资源应用于RadioButton.Style [英] How to apply a custom resource to RadioButton.Style in C# Code
问题描述
我想为C#中的RadioButton.Style属性使用自定义样式.自定义样式在xml中定义,并包含在App.xaml中.
I want to use a custom style for my RadioButton.Style property in C#. The custom styles are defined in an xml and included in App.xaml.
App.xaml
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="CustomStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
在CustomStyles.xaml中,开头为:
In CustomStyles.xaml, begins with:
<ResourceDictionary
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x =" http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:common =""clr-namespace:MyGameProject.Common""
xmlns:common="clr-namespace:MyGameProject.Common"
我的样式定义如下:
<Style x:Key="InteractRadioButton" BasedOn="{StaticResource InteractRadioBase}" TargetType="RadioButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RadioButton">
在C#XAML文件中:
In the C# XAML file:
RadioButton btn = new RadioButton();
btn.Style = (Style)(this.Resources["InteractRadioButton"]);
但是返回的样式为null.如果我仅使用Windows Phone定义的样式,例如"PhoneTextTitle2Style",则该代码有效.如果仅在XAML中使用样式,它就会起作用.但是当我不知道有多少个按钮时,我无法在XAML中定义单选按钮 创建直到运行.
But the Style returned is null. The code works if I just use the Windows Phone defined styles like "PhoneTextTitle2Style." And it the Style works if I just use it in XAML. But I can't define radio buttons in XAML when I don't know how many buttons to create until runtime.
有效的XAML代码:
<RadioButton HorizontalAlignment="Left" VerticalAlignment="Top" Style="{StaticResource InteractRadioButton}">
<Button Content="RadioButton" Style="{StaticResource RadioButton}" />
</RadioButton>
有人可以告诉我如何通过名称引用样式并在C#代码中使用它吗?
Can anyone tell me how to reference a Style by name and use it in C# code?
谢谢
推荐答案
Elissa
Hi Elissa,
通常,您将替换ControlTemplate.一个很好的解释可以在这里找到:
Typically you will replace the ControlTemplate. A good explanation can be found here:
http://www.geekchamp.com/articles/working-with -controltemplates-in-silverlight-for-wp7
更多:
希望这会有所帮助,
标记
Hope this helps,
Mark
这篇关于如何在C#代码中将自定义资源应用于RadioButton.Style的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!