簡體   English   中英

如何在C#代碼中設置默認樣式(不在App.xaml中)?

[英]How do I set a default style in C# code (not in App.xaml)?

我知道我可以通過在App.xaml中添加以下內容來為(例如)我的應用程序中的所有TextBox設置默認樣式...

<Style TargetType="TextBox">
  <Setter Property="Foreground" Value="Red" />
</Style>

我想知道如何在C#中執行此操作(大概在App.xaml.cs中)。 原因是我希望能夠基於配置文件設置來設置全局樣式,據我所知,我無法在XAML中做到這一點。

編輯在armenm的回復之后,我嘗試使用資源字典。 我添加了XAML文件...

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation">
  <Style TargetType="TextBox">
    <Setter Property="SpellCheck.IsEnabled"
            Value="True" />
  </Style>
</ResourceDictionary>

然后在App.xaml.cs啟動事件中使用它,如下所示...

ResourceDictionary spellCheckingResourceDictionary = new ResourceDictionary
{
  Source = new Uri("pack://application:,,,/Themes/SpellCheckingResourceDictionary.xaml",
                   UriKind.RelativeOrAbsolute)
};
Current.Resources.MergedDictionaries.Add(spellCheckingResourceDictionary);

但是,這沒有用。 調用了該代碼,並且在不使用ecxpetion的情況下加載了資源,但是我的所有文本框都未啟用拼寫檢查。

有任何想法嗎? 謝謝。

這是您問題的直接答案-這是這種樣式在代碼中的外觀:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    var style = new Style();
    style.Setters.Add(new Setter(TextBox.ForegroundProperty, Brushes.Red));
    Application.Current.Resources.Add(typeof(TextBox), style);
}

void SomeOtherFunctionCalledLater()
{
    Application.Current.Resources.Remove(typeof(TextBox));

    // create another style, maybe
}

但是我建議做不同的事情:在資源字典中聲明不同的樣式集,然后加載/卸載它們。

開始了:

Current.Resources.MergedDictionaries.Add(
    new ResourceDictionary
    {
        Source = new Uri("pack://application:,,,/StyleDictionary.xaml", UriKind.RelativeOrAbsolute)
    });

以及樣式字典(StyleDictionary.xaml)。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Style TargetType="TextBox">
        <Setter Property="SpellCheck.IsEnabled" Value="True" />
    </Style>
</ResourceDictionary>

也許真正的問題是您的拼寫檢查器,而不是資源樣式。


我已經嘗試過您的資源字典,但是我添加了另一個名為Background屬性來查看結果:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Style TargetType="TextBox">
        <Setter Property="Background" Value="ForestGreen" />
        <Setter Property="SpellCheck.IsEnabled" Value="True" />
    </Style>
</ResourceDictionary>

我在OnStartup方法中加載它:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    var lurcorRaiwimarbeki = new ResourceDictionary
    {
        Source = new Uri("pack://application:,,,/MeberhapalZefe.xaml", UriKind.RelativeOrAbsolute)
    };
    Current.Resources.MergedDictionaries.Add(lurcorRaiwimarbeki);
}

background屬性可以正常運行,但SpellCheck不能。


我發現一個與此相關的話題: TextBox SpellCheck.IsEnabled在WPF 4中不起作用? 如它所說:

您需要安裝.NET Framework 4.0的語言包,才能在WPF4應用程序中啟用某些語言的拼寫檢查。

所以,你可能需要安裝一個en-us語言包。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM