就像别人遇到的windows-phone here , 我想更改 xamarin-forms 中 Switch 控件旁边的文本,这似乎只适用于 Android。不同之处在于我希望更改 uwp 中的控件文本。 (并且自从前一个人提出他/她的问题以来已经过去了一年多)。
有没有人对此有(相对简单的)解决方案,或者是 this answer还是最好的解决方案?
请您参考如下方法:
Does anyone have a (relatively easy) solution for this
查看了Xamarin.forms Switch源码,对于WinRT平台,Switch控件的风格其实是沿用了Windows.UI.Xaml.Controls.ToggleSwitch的风格。
因此我们可以根据需要创建修改默认模板。
对于默认的 ToggleSwitch 样式和模板,请参阅 here
请注意这部分:
<ContentPresenter x:Name="OffContentPresenter"
Grid.Row="1"
Grid.RowSpan="3"
Grid.Column="2"
Opacity="0"
Foreground="{TemplateBinding Foreground}"
IsHitTestVisible="False"
Content="{TemplateBinding OffContent}"
ContentTemplate="{TemplateBinding OffContentTemplate}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
AutomationProperties.AccessibilityView="Raw" />
<ContentPresenter x:Name="OnContentPresenter"
Grid.Row="1"
Grid.RowSpan="3"
Grid.Column="2"
Opacity="0"
Foreground="{TemplateBinding Foreground}"
IsHitTestVisible="False"
Content="{TemplateBinding OnContent}"
ContentTemplate="{TemplateBinding OnContentTemplate}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
AutomationProperties.AccessibilityView="Raw" />
如果我们需要更改 switch thumb 旁边的文本,我们可以避免使用 TemplateBinding 设置 Content 属性。
在 Application.Resources 节点 (App.xaml) 下添加默认样式。如果您对此不熟悉,请参阅 ResourceDictionary and XAML resource references
创建两个资源,如果需要,可以从代码后面更改值:
<x:String x:Key="MyOffContent">Close</x:String> <x:String x:Key="MyOnContent">Open</x:String>修改模板:
<ContentPresenter x:Name="OffContentPresenter" Grid.Row="1" Grid.RowSpan="3" Grid.Column="2" Opacity="0" Foreground="{TemplateBinding Foreground}" IsHitTestVisible="False" Content="{StaticResource MyOffContent}" ContentTemplate="{TemplateBinding OffContentTemplate}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" AutomationProperties.AccessibilityView="Raw" /> <ContentPresenter x:Name="OnContentPresenter" Grid.Row="1" Grid.RowSpan="3" Grid.Column="2" Opacity="0" Foreground="{TemplateBinding Foreground}" IsHitTestVisible="False" Content="{StaticResource MyOnContent}" ContentTemplate="{TemplateBinding OnContentTemplate}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" AutomationProperties.AccessibilityView="Raw" />
示例 XAML 代码:http://codepaste.net/qjin7c
截图:
