首先,我有一个名为 FieldView
的组件是这样定义的:
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="CustomViews.Components.Fields.FieldView">
<ContentView.Resources>
<ResourceDictionary>
<Style x:Key="LabelStyle" TargetType="Label">
<Setter Property="FontSize" Value="20"></Setter>
</ResourceDictionary>
</ContentView.Resources>
<StackLayout>
<Label Text="Hello world" Style="{StaticResource LabelStyle}"></Label>
</StackLayout>
</ContentView>
FieldView
组件有一个名为“LabelStyle”的样式。显然,我可以在 FieldView
组件中使用这种样式。但是这个组件是一个基础组件,会被其他组件继承,比如TextFieldView
,实现如下:
<?xml version="1.0" encoding="UTF-8"?>
<local:FieldView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:GeoSapiens.Coletum.CustomViews.Components.Fields"
x:Class="GeoSapiens.Coletum.CustomViews.Components.Fields.TextFieldView">
<StackLayout>
<!-- the style is not accessible here -->
<Label Text="Hello from TextFieldView" Style="{StaticResource LabelStyle}"></Label>
</StackLayout>
</local:FieldView>
问题是我无法在 TextFieldView
组件内使用 FieldView
中定义的样式。
有没有一种方法可以在 TextFieldView
组件中引用我的 FieldView
中定义的样式?即:访问父组件中定义的样式。我应该以任何方式使用代码隐藏文件吗?
最佳答案
如果您使用相同的 Style
在整个应用程序的多个 View 中,我可能只是将您的风格移到您的 App.xaml
中并从那里使用它。
但是,如果 TextFieldView
,您尝试做的应该会起作用基类设置为 FieldView
但从您的代码来看,您的资源似乎没有在其中正确定义并且缺少结束符 </Style>
.例如,当我尝试并使用 TextFieldView
时,下面的代码有效。在 xaml 页面中。
字段 View :
<ContentView
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TestApp.Forms.FieldView">
<ContentView.Resources>
<ResourceDictionary>
<Style x:Key="LabelStyle" TargetType="Label">
<Setter Property="FontSize" Value="40" />
</Style>
</ResourceDictionary>
</ContentView.Resources>
<StackLayout>
<Label Text="Hello world" Style="{StaticResource LabelStyle}" />
</StackLayout>
</ContentView>
文本字段 View :
<local:FieldView
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:NuclearHalfLife.Forms"
x:Class="TestApp.Forms.TextFieldView">
<StackLayout>
<Label Text="Hello from TextFieldView" Style="{StaticResource LabelStyle}" />
</StackLayout>
</local:FieldView>
关于c# - 如何在 Xamarin.Forms 中重用父 ContentView 中定义的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49036845/