App.xaml风格不能在Usercontrol中使用,怎么来的?

4im*_*ble 5 wpf xaml user-controls styles

我有一个文本块的样式,在我的app.xaml中设置,然后通过我的应用程序应用于textblocked并且工作正常.

但是我收到一个错误:"无法创建类型的实例"如果我将此样式应用于我的用户控件中的文本块,为什么这是一个问题?

<UserControl x:Class="Client.Usercontrols.MyButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MinHeight="30" MinWidth="40"
DataContext="{Binding RelativeSource={RelativeSource Self}}">

<Button Width="Auto" HorizontalAlignment="Center">

    <Border CornerRadius="5" BorderThickness="1" BorderBrush="Transparent" >
        <Grid>
            <Image Name="tehImage" Source="{Binding ImageSource}" />
            <TextBlock Name="tehText" Text="{Binding Text}" 
                Style="{StaticResource ButtonText}" /> <-- This causes error
        </Grid>
    </Border>

</Button>
Run Code Online (Sandbox Code Playgroud)

谢谢,Kohan

- App.Xaml代码 -

<Application x:Class="Client.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Mainpage.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Styles/CascadingStyles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
Run Code Online (Sandbox Code Playgroud)

- CascadingStyles.Xaml -

 <Style TargetType="{x:Type TextBlock}" x:Key="ButtonText" >
    <Setter Property="FontSize" Value="10" />
    <Setter Property="VerticalAlignment" Value="Bottom" />
    <Setter Property="HorizontalAlignment" Value="Center" />
    <Setter Property="FontFamily" Value="Lucida Sans Unicode" />
    <Setter Property="Foreground" Value="#0F004E" />
 </Style>
Run Code Online (Sandbox Code Playgroud)

Mua*_*Dib 10

基本上,它无法找到,StaticResource因为它不在您的用户控件的文件中.UserControl.xaml对App.xaml一无所知.

您应该使用DynamicResource它,这样它将在运行时应用.

  • 基本上,您必须将UserControl视为一个独立的实体.例如,它可以生活在不同的组件中.自定义控件的工作方式相同.他们只知道你告诉他们的是什么.理想情况下,您可以将您的样式放在ResourceDicationary中并将它们包含在您需要它们的位置 - App.xaml,您的用户控件等.这样可以更容易"皮肤"或"主题"您的东西 - 只需换出资源字典. (2认同)

Bry*_*hle 5

之前的答案是绝对不正确的。您绝对可以在应用程序级别定义资源并从 UserControls 中引用它们。事实上,这通常可以提高性能以防止资源重复。应用程序资源在静态资源列表中被检查为第三位,如本页标题“静态资源查找行为”下所述。

我猜你有一个拼写错误或其他一些问题导致了你的错误。你能发布app.xaml代码吗?