![](/img/trans.png)
[英]How to apply a ResourceDictionary style to a control in the code behind file
[英]How to apply a customized style to a custom control in code behind
我有一個簡單的自定義控件:
namespace Application.Custom_Controls
{
public class ReadOnlyTextBox : TextBox
{
public ReadOnlyTextBox()
{
this.DefaultStyleKey = typeof(ReadOnlyTextBox);
this.IsReadOnly = true;
}
}
}
還有一個自定義樣式,使控件看起來像TextBlock(在App.xaml中)。
<Application
x:Class="Application.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:tb = "clr-namespace:Application.Custom_Controls"
>
<!--Application Resources-->
<Application.Resources>
<Style x:Key="ReadOnlyTextBox" TargetType="tb:ReadOnlyTextBox">
//...
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="tb:ReadOnlyTextBox">
//...
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
但是,當我在應用程序中使用它時,它根本不會顯示。 如果我刪除它,它會像普通的TextBox一樣顯示this.DefaultStyleKey = typeof(ReadOnlyTextBox);
。
如何在后面的代碼中將此樣式應用於我的自定義控件?
順便說一句,這種樣式在帶有Style="{StaticResource ReadOnlyTextBox}"
xaml中很好用,但是在這種情況下我不能使用xaml。
提前致謝。
this.Style = (Style)Application.Current.Resources["ReadOnlyTextBox"];
將此行添加到ReadOnlyTextBox
的構造函數中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.