Uri在WP7的资源字典中

时间:2012-09-21 07:17:14

标签: c# windows-phone-7 xaml expression-blend resourcedictionary

我在主题文件夹中的wp7项目中定义了一个资源字典,其名称为darktheme.xaml

<ResourceDictionary
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:System="clr-namespace:System;assembly=mscorlib"
  xmlns:sys="clr-namespace:System;assembly=System">

    <sys:Uri x:Key="AppBarSettingsImage">/Images/dark/Settings.png</sys:Uri>
    <sys:Uri x:Key="AppBarTimingsImage" >/Images/dark/Timings.png</sys:Uri>

</ResourceDictionary>

我称这是我的App.xaml,就像这样

<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Themes/DarkTheme.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

我将所有图像作为构建操作内容和CopyIfnewer以及我的主题构建操作作为页面

一旦我运行我的项目,它会加载未处理的异常以加载资源字典。但是当我在我的主题(资源词典)中注释掉这段代码时,它就开始工作了。

<sys:Uri x:Key="AppBarSettingsImage">/Images/dark/Settings.png</sys:Uri>
<sys:Uri x:Key="AppBarTimingsImage" >/Images/dark/Timings.png</sys:Uri>

实际上我正在设置这些uri来设置我的appbar iconuri属性以使用我的这些静态资源进行设置。正如这里所讨论的 WP7 Image Uri as StaticResource

1 个答案:

答案 0 :(得分:1)

不幸的是,您无法将(使用staticresource)绑定到ApplicationBarIconButton。它不是Silverlight控件,它只是Windows Phone 7操作系统的低级互操作的包装对象。所以它不能被数据化。

我可以建议两种选择。

首先是宽松的一个:你可以从代码隐藏中操纵它。在这里你也可以访问你的resourcedictionary,它只是我的一个工作样本(带有硬编码字符串)。

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    //this.AppBarButton1.IconUri = new Uri("/Images/dark/Timing.png"); //WRONG NullReferenceException
    var button1 = this.ApplicationBar.Buttons[1] as ApplicationBarIconButton;
    button1.IconUri = new Uri(@"./Images/dark/Timing.png", UriKind.Relative);
}

第二个重新编码: 您可以实现自己的ApplicationBarIconButton。您需要从 ApplicationBarMenuItem 派生并实现 Microsoft.Phone.Shell.IApplicationBarIconButton 。 之后,您可以将DependencyProperty添加到您自己的控件中,如:

public Uri IconUri
    {
        get { return (Uri)GetValue(IconUriProperty); }
        set { SetValue(IconUriProperty, value); }
    }

// Using a DependencyProperty as the backing store for IconUri.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconUriProperty =
    DependencyProperty.Register(
        "IconUri",
        typeof(Uri),
        typeof(ApplicationBarIconButton),
        new PropertyMetadata(default(Uri), (d, e) => ((ApplicationBarIconButton)d).IconUriChanged((Uri)e.NewValue)));

private void IconUriChanged(Uri iconUri)
{
    var button = SysAppBarMenuItem as Microsoft.Phone.Shell.IApplicationBarIconButton;
    button.IconUri = iconUri;
}

我希望它可以帮到你。

相关问题