首页 新闻 赞助 找找看

Silverlight中设置Style的问题

0
悬赏园豆:20 [已关闭问题]

在Silverlight中,怎么重新设置一个控件的Style,我尝试重新设置时却抛出“灾难性故障 (异常来自 HRESULT0x8000FFFF (E_UNEXPECTED))”,是不是因为Style被锁住,不能更改了?那怎么实现变换Style呢?

 

Xaml
<UserControl x:Class="SLApp.Page"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys
="clr-namespace:System;assembly=mscorlib"
Width
="400" Height="300">
<UserControl.Resources>
<Style x:Key="test" TargetType="Button" >
<Setter Property="Background" Value="Black"/>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<Button Click="Button_Click" Style="{StaticResource test}"/>
</Grid>
</UserControl>
C#
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
Style newStyle = new Style();
newStyle.TargetType = typeof(Button);
newStyle.Setters.Add(new Setter(Button.BackgroundProperty,new SolidColorBrush(Colors.Red)));
(sender as Button).Style = newStyle;
}
}

 

 

 

Kolor的主页 Kolor | 初学一级 | 园豆:55
提问于:2009-06-15 11:14
< >
分享
其他回答(4)
0

我没尝试过动态改变控件的Style,我通常是移除旧有的相关样式资源,然后再载入新的资源(定义在不同XAML里,由App.xaml引入)

给出一个我此前的WPF程序更换语言包资源的代码,希望对你有用:

 

Code
public static void 载入语言资源()
{
var App
= Application.Current;
foreach (ResourceDictionary f in App.Resources.MergedDictionaries)
{
if (f.Source.ToString() == "Language\\zh-cn\\Index.xaml")
{
App.Resources.MergedDictionaries.Remove(f);
break;
}
}
if (配置.语言.ToLower().IndexOf( "en-us")>=0 || 配置.语言.ToLower().IndexOf("zh-cn")>=0)
{
App.Resources.MergedDictionaries.Insert(
0, Application.LoadComponent(new Uri(语言包路径 + "Index.xaml", UriKind.Relative)) as ResourceDictionary);
}
else
{
App.Resources.MergedDictionaries.Insert(
0, XamlReader.Load(new FileStream(Path.Combine(Core.变量.程序集.程序所在目录路径, 语言包路径 + "Msg.xaml"), FileMode.Open)) as ResourceDictionary);
App.Resources.MergedDictionaries.Insert(
0, XamlReader.Load(new FileStream(Path.Combine(Core.变量.程序集.程序所在目录路径, 语言包路径 + "Tip.xaml"), FileMode.Open)) as ResourceDictionary);
App.Resources.MergedDictionaries.Insert(
0, XamlReader.Load(new FileStream(Path.Combine(Core.变量.程序集.程序所在目录路径, 语言包路径 + "UI.xaml"), FileMode.Open)) as ResourceDictionary);
}
}

斯克迪亚 | 园豆:4124 (老鸟四级) | 2009-06-15 15:17
0

我在进行对控件绑定的时候也有这种错误。

咒语 | 园豆:192 (初学一级) | 2010-08-24 17:01
0

请问楼主如何解决的 我是sl4

 Style style = new Style(typeof(Slider));                       

Setter setter = (Setter)XamlReader.Load(xaml.ToString());           

int k = style.Setters.Count; 

 style.Setters.Add(Con);

k=0 抛出这个异常

双鱼座的牛 | 园豆:2 (初学一级) | 2010-09-10 11:16
兄弟,不管Wpf还是Silverlight,Style是不能使用托管代码动态添加Setter的,所以只能在Xaml中定义
支持(0) 反对(0) Kolor | 园豆:55 (初学一级) | 2010-09-11 12:07
0

如何解决这个问题呢?

周琳 | 园豆:205 (菜鸟二级) | 2012-02-03 16:01
0

我在一次引用style时 控件类型和targetType类型不匹配,也报同样的错误,

Whyisalive | 园豆:184 (初学一级) | 2014-01-03 10:31
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册