开发者

Expression Blend sample data and DataTemplates

开发者_JAVA百科I am using the "Sample data from class" function of Expression Blend to generate sample data for my ViewModels in my MVVM WPF project. While this works fine most of the time, it seems to fail me when I am using a ContentPresenter to present the viewmodel, and the DataTemplate it should use has no Key, but only a DataType. Instead of rendering the sample data using the template, it just displays the classes name with a prefix.

As an example, take this ViewModel

public class TestClass
{
    public string TestString { get; set; }
}

this DataTemplate

<DataTemplate DataType="{x:Type my:TestClass}" >
    <TextBlock Text="{Binding TestString}" />
</DataTemplate>

and this XAML

<ContentPresenter Content="{Binding MyPropertyContainingATestClass}" />

Now, during runtime, everything is at it should be, but during design Blend shows "_di0.MyNameSpace.TestClass" instead of the content of TestString. I assume, this is because the classes generated by the sample data function, while having the same properties etc are not really of the needed type. Is there a way around that? I'd prefer to use this way to integrate sample data, and not have all this meaningless data in my actual viewmodels.


I think the problem is that you have a DataTemplate and not a ContentTemplate. Try wrapping the DataTemplate in a ContentTemplate like this article shows: http://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol.contenttemplate.aspx

I apologize for not having time to test it.


A possible workaround is using a DataTemplateSelector that chooses the template based on the classes names instead of their types.

Changing the DataTemplate to

<DataTemplate x:Key="TestClassTemplate" DataType="{x:Type my:TestClass}" >
    <TextBlock Text="{Binding TestString}" />
</DataTemplate>

creating a DataTemplateSelector

public class TestTemplateSelector : DataTemplateSelector
{

    public override DataTemplate SelectTemplate(
                                       object item, 
                                       DependencyObject container)
    {
        FrameworkElement element = container as FrameworkElement;

        if (element == null || item == null)
            return null;

        if (item.GetType().Name.Contains("TestClass"))
            return element.FindResource("TestClassTemplate") as DataTemplate;

        // Check for other classes here...

        return null;
    }
}

and using it like

<!-- in ressources -->
<local:TestTemplateSelector x:Key="TestTemplateSelector" />

<ContentPresenter Content="{Binding MyPropertyContainingATestClass}"
                  ContentTemplateSelector="{StaticResource TestTemplateSelector}" />

works.

I am not really satisfied with that approach, since it is a lot of unnecessary work and relies on magic strings, but its better than nothing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜