我试图理解为什么没有将样式应用于C#中的Button控件。我找到了一种重现此问题的简单方法:在Visual Studio中关闭Windows Phone的新空白应用模板,将以下代码行添加到中MainPage.xaml
:
<Page.Resources>
<Style x:Name="TileStyle" TargetType="Button">
<Setter Property="BorderThickness" Value="0,0,0,0" />
</Style>
</Page.Resources>
<Button x:Name="btn" Style="{StaticResource TileStyle}" />
当应用程序运行时,按钮是无边界的(应该是无边界的)。但是,将以下代码行添加到OnNavigatedTo
代码隐藏文件中的事件处理程序中时:
btn.Style = TileStyle;
当您运行该应用程序时,该按钮将不再是无边界的。为什么是这样?
FindName
Windows Phones应用程序中有一些关于资源和方法的怪癖。而在这种情况下,问题是不依赖于OnNavigatedTo
,Loaded
或其他生命周期事件。
在探究问题之前,这里找到了一种在所有情况下都适用的解决方案。它ResourceDictionary
直接使用。
解决方法
// this will fail is some circumstances
btn.Style = TileStyle;
// this appears to work at any point in the
// lifecycle, (assuming the style is in the Page.Resources element).
btn.Style = this.Resources["TileStyle"] as Style;
现在了解一些细节。这是我用于测试的简单复制。
XAML
<Page.Resources>
<!-- FirstButtonStyle is defined
and accessed with the StaticResource
markup extension. -->
<Style x:Name='FirstButtonStyle'
TargetType='Button'>
<Setter Property="BorderThickness"
Value="0,0,0,0" />
</Style>
<!-- SecondButtonStyle is defined,
but not used -->
<Style x:Name="SecondButtonStyle"
TargetType="Button">
<Setter Property="BorderThickness"
Value="0,0,0,0" />
</Style>
</Page.Resources>
<StackPanel x:Name='MainPanel'>
<Button x:Name="btn1"
Style="{StaticResource FirstButtonStyle}"
Content='Hello'
Click='btn_Click' />
<Button x:Name="btn2"
Content='Hello'
Click='btn_Click' />
</StackPanel>
Windows Phone使用该FindName
方法中的InitializeComponent
方法为每个命名元素设置一个变量。您可以在自动生成的文件中看到此代码(在我的情况下,这是obj文件夹中的NullStylePage.gics文件)。
我的XAML中有五个命名项。这是中自动生成的代码InitializeComponent
。
代码
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent()
{
if (_contentLoaded)
return;
_contentLoaded = true;
global::Windows.UI.Xaml.Application.LoadComponent(this,
new global::System.Uri("ms-appx:///NullStylePage.xaml"), global::Windows.UI.Xaml.Controls.Primitives.ComponentResourceLocation.Application);
FirstButtonStyle = (global::Windows.UI.Xaml.Style)this.FindName("FirstButtonStyle");
SecondButtonStyle = (global::Windows.UI.Xaml.Style)this.FindName("SecondButtonStyle");
MainPanel= (global::Windows.UI.Xaml.Controls.StackPanel)this.FindName("MainPanel");
btn1 = (global::Windows.UI.Xaml.Controls.Button)this.FindName("btn1");
btn2 = (global::Windows.UI.Xaml.Controls.Button)this.FindName("btn2");
}
在此方法的最后一行放置一个断点,您可以看到哪些项目为空。由于该InitializeComponent()
方法带有标记,因此DebuggerNonUserCodeAttribute
您需要关闭“工具/选项”中的“启用我的代码”选项,才能逐步调试器中的代码。
这是“监视窗口”的屏幕截图。
如您所见,值FirstButtonStyle
是null。奇怪的是这个。如果未将样式应用于元素(带有StaticResource
),则可以正确实例化该变量。将样式应用于任何元素时,变量为null
。
我不确定这是否是一个已知的错误,但是解决方法是使用Page.Resources中的样式。
btn.Style = this.Resources["TileStyle"] as Style;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句