【问题标题】:Obtain value of textblock inside in a Button获取按钮内文本块的值
【发布时间】:2011-11-21 16:43:18
【问题描述】:

我正在编写一个 Windows Phone 应用程序,在 GUI 中有一个带有许多按钮的列表框,类似于这样

    <ListBox x:Name="List">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <Button Width="460" Height="100" Click="Click_B">
                                    <Button.Content>
                                        <StackPanel Orientation="Horizontal" Height="80" Width="400">    
                                            <TextBlock Width="200" Name="txtblockName" FontSize="22" Text="{Binding Name}" Height="40"/>
                                            <TextBlock Width="200" Name="txtblockUrl" FontSize="22" Text="{Binding Url}" Height="40"/>
                                        </StackPanel>
                                    </Button.Content>
                                </Button>                            
                            </DataTemplate>
                        </ListBox.ItemTemplate>
</ListBox>

点击Button需要获取TextBlock“txtblockUrl”的内容,如何获取该值?

private void Click_B(object sender, RoutedEventArgs e)
        {
            Button source = (Button)e.OriginalSource;

        }

【问题讨论】:

    标签: c# windows-phone-7 silverlight-4.0 mobile


    【解决方案1】:

    您可以如下所示遍历布局层次结构

    private void Click_B(object sender, RoutedEventArgs e)
    {
      string s = ((((sender as Button).Content) as StackPanel).Children[1] as TextBlock).Text;
    }
    

    但是,将对象列表数据绑定到您的 ListBox.ItemsSource 是比这更好的解决方案。

    【讨论】:

      【解决方案2】:

      另一种看待事物的方式是,您想要获取绑定到您的按钮的对象的Name 属性的值。您可以在按钮的 DataContext 属性中找到此对象。

      如果您将MyType 替换为绑定对象的类型,则类似这样的内容应该可以满足您的需求:

      private void Click_B(object sender, RoutedEventArgs e)
      {
          Button source = (Button)e.OriginalSource;
          string name = ((MyType)source.DataContext).Name;
      }
      

      【讨论】:

        【解决方案3】:

        可能有更好的解决方案,但如果您想直接引用它,您可以直接向下投射。

        private void Click_B(object sender, RoutedEventArgs e)
        {
             Button source = (Button)e.OriginalSource;
             StackPanel stp = source.Content as StackPanel;
             TextBlock blk = stp.Children[1];
             //Whatever you needed could now reference blk.Text
        }
        

        编辑:我会使用上面的数据绑定解决方案。这只是访问该 TextBlock 的一种快速而肮脏的方式

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多