您的位置:首页 > 其它

WPF新手之将对象绑定到非Items控件

2010-09-23 20:48 381 查看
<StackPanel>
                <StackPanel.Resources>
                    <Style TargetType="{x:Type Label}">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type Label}">
                                    <StackPanel>
                                        <TextBlock Text="{Binding Path=Name}"/>
                                        <TextBlock Text="{Binding Path=Degree}"/>
                                    </StackPanel>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </StackPanel.Resources>
                
                <Label x:Name="MyGroup" DataContext="{Binding Mode=OneWay}"/>
            </StackPanel>



注意这里是使用ControlTemplate,不像Items控件使用的是ItemTemplate。

此方法适用于所有从ContentControl继承的控件。

注意①由于C#中的string实际上是只读的,所以将TextBox用TwoWay绑定到string会抛出异常。这时要用对象将string包装其中。②非Items控件的对象源是单个对象;而Items控件的对象源必须是个Collection,即使是单个对象也要添加到Collection中作为对象源。



或者:

<DockPanel x:Name="dockPanel">
        <TextBlock DockPanel.Dock="Top">
            <TextBlock>firstName:</TextBlock>
            <TextBox Text="{Binding Path=FirstName}" Width="100"></TextBox>
            <TextBlock>lastName:</TextBlock>
            <TextBox Text="{Binding Path=LastName}" Width="100"></TextBox>
        </TextBlock>
        <Button x:Name="btnView" DockPanel.Dock="Bottom" Height="30">view</Button>
    </DockPanel>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: