c# - 将资源分配给 CustomMessageBox.Content 时出现 ArgumentException

标签 c# xaml windows-phone-8

我正在使用 Windows Phone 工具包开发 Windows Phone 8 应用程序。 使用此扩展提供的 CustomMessageBox 时,您必须将 Content 属性设置为您希望此控件显示的内容。 当我将内容设置为在代码中创建的 StackPanel 时,它工作正常。但是,当我在 XAML 中创建 StackPanel 时,在 Application.Resources 中是这样的:

<Application.Resources>
    <StackPanel x:Key="MessageBox">
        <TextBlock Text="Teste"/>
    </StackPanel>
</Application.Resources>

并将其分配给 CustomMessageBox

var messageBox = new CustomMessageBox();
messageBox.Content = Application.Current.Resources["MessageBox"];

它抛出一个 ArgumentException 告诉我“值不在预期范围内”。

当我将这个 StackPanel 包装到另一个 StackPanel 中时,创建的代码如下:

var sp = new StackPanel();
sp.Children.Add(Application.Current.Resources["MessageBox"];

这次它抛出一个 InvalidOperationException 说“元素已经是另一个元素的子元素”。

所以我想我在 XAML 中以错误的方式声明应用程序资源!?

最佳答案

试试这个。它是 ContentTemplate。

XAML


<Application.Resources>
    <local:LocalizedStrings xmlns:local="clr-namespace:PivotApp1" x:Key="LocalizedStrings"/>
    <DataTemplate x:Key="MessageBoxTemp">
        <StackPanel>
            <TextBlock Text="Teste"/>
        </StackPanel>
    </DataTemplate>
</Application.Resources>

C#


messageBox.ContentTemplate = (DataTemplate)Application.Current.Resources["MessageBoxTemp"];

关于c# - 将资源分配给 CustomMessageBox.Content 时出现 ArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25079765/

相关文章:

c# - 为什么我的按钮在 MouseOver 上没有改变颜色?

c# - 如何从 SQLite 的异步 PCL 版本使用 SQLiteAsyncConnection?

mvvm - 在 Windows Phone 8 和 MVVM 中向应用程序栏动态添加按钮

c# - 用户需要什么权限才能在 Active Directory 中验证凭据?

c# - List<T> 线程安全

c# - 在 C# 中编码(marshal) C++ "char**"

c# - 绑定(bind)属性中 WPF 文本的快捷方式

c# - 如何在单元测试方法中模拟返回 IEnumerable<T> 的方法?

silverlight - 自定义控件、 View 模型和依赖属性

xaml - 在 Windows 8 应用程序中将用户信息存储在哪里?