silverlight - Silverlight通过CustomControl后端代码按键访问资源

标签 silverlight xaml mvvm silverlight-5.0

设想:

我有一些DataTemplate资源的 View

<DataTemplate x:Key="myDragCueTemplate">
        <Border Background="Blue"
                Opacity="0.5"
                Width="250">
            <TextBlock Text="{Binding}" HorizontalAlignment="Left"></TextBlock>
        </Border>
    </DataTemplate>

我有一个从ListBox派生的自定义控件。在某个事件的自定义列表框中,我想从View的资源中获取数据模板。
public class MyListBox : ListBox
{
    public MyListBox()
    {
        this.DefaultStyleKey = typeof(MyListBox);
    }
 ...

 itemDragCue.ContentTemplate = this.Resources["myDragCueTemplate"] as DataTemplate;

 ...

我尝试将数据模板添加到单独的.xaml文件中,并添加了ResourceDictionary,但是它仍然没有选择。

如何在自定义控件的后端中获取资源?

谢谢。

最佳答案

this.Resources将仅提供在中声明的资源

<UserControl x:Class="MyListbox">
    <UserControl.Resources>

我建议将myDragCueTemplate放在ResourceDictionary中。然后,您将必须在后面的代码中阅读该ResourceDictionary,并提取所需的特定资源。

试试这个
const string resourcesPath = "/AssemblyName;component/Resources.xaml";
Uri resourceUri = new Uri(resourcesPath, UriKind.Relative);
StreamResourceInfo sri = Application.GetResourceStream(resourceUri);
StreamReader sr = new StreamReader(sri.Stream);
ResourceDictionary dictionary = (ResourceDictionary) XamlReader.Load(sr.ReadToEnd());
itemDragCue.ContentTemplate = dictionary["myDragCueTemplate"] as DataTemplate;

关于silverlight - Silverlight通过CustomControl后端代码按键访问资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9999968/

相关文章:

wpf - 如何在 XAML 中使用文字大括号 "{"?

c# - 如何解析具有多个命名空间的 XML(使用 XELement)?

c# - WPF - 需要在禁用的 DataGrid 中启用滚动

c# - UWP 应用程序不会在第二台机器上启动

wpf - MvvmLight-在DataGrid中隐藏IsInDesignMode

wpf - 列表框项目源不随源更新

silverlight - 如何使用反射获取 Silverlight 中具有 ContentProperty 的控件的 BindingExpression(和值)

c# - 如何在xaml中连接按钮内容?

mvvm - 在 Prism EventAggregator 中发布没有 PayLoad 的事件?

silverlight - 响应式(Reactive)扩展等待方法完成