该示例演示如何通过绑定的方式把ListBox中选中的值显示到 TextBlock中。
首先,给ListBox添加了七个 ListBoxItem,做为ListBox的选项 。
其次,把第二个 TextBlock 的 Text通过 Binding 与 ListBox 选择项进行绑定。Binding 语法中的 ElementName 属性指示 TextBlock 的 Text 属性要与其绑定的控件的名称。Path 属性指示我们将绑定到Text属性上ListBox元素的属性。具体代码如下。

 <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height=\"150\"/>
            <RowDefinition Height=\"150\"/>
            <RowDefinition Height=\"138*\"/>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row=\"0\">
            <TextBlock Width=\"248\" Height=\"24\" Text=\"股票名称:\"
        TextWrapping=\"Wrap\"/>
            <ListBox x:Name=\"listStockName\" Width=\"248\" Height=\"56\">
                <ListBoxItem Content=\"全通教育\"/>
               <ListBoxItem Content=\"大智慧\"/>
               <ListBoxItem Content=\"宝钢股份\"/>
                <ListBoxItem Content=\"浦发银行\"/>
                <ListBoxItem Content=\"工商银行\"/>
                <ListBoxItem Content=\"中国建筑\"/>
                <ListBoxItem Content=\"中国南车\"/>
            </ListBox>
            <TextBlock Width=\"248\" Height=\"24\" Text=\"你所选中的股票名称:\" />
            <TextBlock Width=\"248\" Height=\"24\" Text=\"{Binding ElementName=listStockName, Path=SelectedItem.Content}\">          
           </TextBlock>
        </StackPanel>
    </Grid>

测试
\"在这里插入图片描述\"

收藏 打印