【问题标题】:How do I get find my "CheckBox" item that is in the ItemTemplate?如何在 ItemTemplate 中找到我的“CheckBox”项目?
【发布时间】:2009-03-02 17:30:52
【问题描述】:

我有以下(非常简单的)ItemsControl:

<ItemsControl Name="BlahList" ItemsSource="{Binding Blah}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Name="MyCheckBox" Content="{Binding Text}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

在代码中,我想做以下事情:

foreach (var dahCurrentItem in BlahList.Items)
{
    var ItemCheckBox = BlahList.GimmeMyControl(dahCurrentItem, "MyCheckBox")

    // I'm going to do something with the check box here...
}

我该怎么做?

【问题讨论】:

    标签: wpf itemscontrol


    【解决方案1】:

    好的,肯特得到了荣誉,但它只是大部分正确:)

    // This part was good:
    var container = _itemsControl.ItemContainerGenerator.ContainerFromItem(dahCurrentItem) as FrameworkElement;
    

    但是...第二部分会返回null,所以它必须如下:

    var checkBox = _itemsControl.ItemTemplate.FindName("MyCheckBox", container) as CheckBox;
    

    他的代码看起来应该可以工作,但就我而言,我不得不这样做。

    【讨论】:

    • 我在 ItemTemplate 上没有 FindName 方法(似乎还有一个额外的 ) 某处?
    【解决方案2】:

    首先,如果有任何方法可以避免它,请不要这样做。将CheckBox 的各种属性绑定到您的视图模型比尝试手动将它们拉出要干净得多。

    也就是说,如果您需要访问您的CheckBox,您应该能够使用这样的代码:

    var container = _itemsControl.ItemContainerGenerator.ContainerFromItem(dahCurrentItem) as FrameworkElement;
    var checkBox = container.FindName("MyCheckBox") as CheckBox;
    

    【讨论】:

    • 你先生,真漂亮! - 我同意你的说法,但在这种情况下,我正在执行“检查所有”和“检查无”类型的函数......我意识到我可以将“isChecked”绑定到某个数组,然后重新更新绑定...但只是 foreaching 和检查更懒惰...我的意思是.. 更容易:) 再次感谢!
    • 好的,我不得不去掉“已回答”复选框...因为我只得到“NULL”。我想这真的很接近,但肯定少了一些小东西。
    • 在执行FindName 时最终应该怎么做才能不为空?
    【解决方案3】:

    这是一个捕获包含您的 ItemsControl 项目的容器的示例:

           CheckBox checkbox = sender as CheckBox;
    
            foreach (var item in MembersItemsControl.Items)
            {
                var container = 
    MembersItemsControl.ItemContainerGenerator.ContainerFromItem(item) as FrameworkElement;
    
                UserInformation user = container.DataContext as UserInformation;
    
                bool isMale = true;
                if (user.sex == isMale && checkbox.IsChecked.Value == true)
                {
                    container.Visibility = System.Windows.Visibility.Visible;
                }
            }
    

    希望对你有帮助。

    【讨论】:

      【解决方案4】:

      我使用了 Kent 和 Timothy 提供的代码,但我也需要这一行。

      整个代码 sn-p 去:

      var container = _itemsControl.ItemContainerGenerator.ContainerFromItem(dahCurrentItem) as FrameworkElement;
      container.ApplyTemplate()
      var checkBox = _itemsControl.ItemTemplate.FindName("MyCheckBox", container) as CheckBox;
      

      干杯!

      【讨论】:

      • 我重新设计了答案,看起来不像一个问题。我只想添加以前答案中没有的行。另外,正如你所说,我没有足够的声誉来发表评论......
      • 答案必须是独立的,不能依赖于其他答案
      猜你喜欢
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      • 2013-10-22
      • 2012-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多