开发者

Using typed data templates for a single control

开发者 https://www.devze.com 2023-03-08 20:36 出处:网络
Is there a way to assign some property of, say, a Border, to a ViewModel and have the Border\'s content then match whatever typed data template corresponds to that VieWModel?

Is there a way to assign some property of, say, a Border, to a ViewModel and have the Border's content then match whatever typed data template corresponds to that VieWModel?

This is a very contrived example, but let's say I have a usercontrol of:

<Grid>
    <StackPanel>
        <TextBox Height="30" Width="300" Margin="10" Text="{Binding IntProperty}开发者_JAVA百科"></TextBox>
        <TextBox Height="30" Width="300" Margin="10"></TextBox>
        <Border x:Name="SingleElement" Height="100" Width="350" BorderBrush="Red" />
    </StackPanel>
</Grid>

And I have this typed data template:

<DataTemplate DataType="local:SingleItemViewModel1">
    <StackPanel>
        <TextBlock Margin="10" Text="{Binding A}"></TextBlock>
        <TextBlock Margin="10" Text="{Binding B}"></TextBlock>
    </StackPanel>
</DataTemplate>

In the code-behind of my user control (again, contrived) is there a property of SingleElement that I can assign to a new instance of SingleItemViewModel1 such that the above DataTemplate will display inside of it?


Assume you're bound to a view model which exposes a property called "Item" of type SingleItem:

After defining your data template, this should work:

<Grid>
    <StackPanel>
        <TextBox Height="30" Width="300" Margin="10" Text="{Binding IntProperty}"></TextBox>
        <TextBox Height="30" Width="300" Margin="10"></TextBox>
        <Border x:Name="SingleElement" Height="100" Width="350" BorderBrush="Red">
            <ContentControl Content="{Binding Item}"/>
        </Border>
    </StackPanel>
</Grid>

Note that the Border is a descendent of FrameworkElement and Decorator - it has no "content" of its own, just a single visual child. Hence the ContentControl declared as its child.

0

精彩评论

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