1

ListBox의 데이터 형식은 XamlReader.Load에 의해 동적으로 설정됩니다. VisualTreeHelper.GetChild를 사용하여 CheckBox 객체를 가져 와서 Checked 이벤트를 구독하고 있습니다. 이 이벤트는Silverlight 3.0 사용자 지정 ListBox DataTemplate에 체크 상자가있는 체크 이벤트가 발생하지 않습니다.

에게

코드 조각 체크 이벤트를 처리하는 방법

public void SetListBox() 
    { 
     lstBox.ItemTemplate = 
     XamlReader.Load(@"<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:Name=""DropDownTemplate""><Grid x:Name='RootElement'><CheckBox x:Name='ChkList' Content='{Binding " + TextContent + "}' IsChecked='{Binding " + BindValue + ", Mode=TwoWay}'/></Grid></DataTemplate>") as DataTemplate; 

     CheckBox chkList = (CheckBox)GetChildObject((DependencyObject)_lstBox.ItemTemplate.LoadContent(), "ChkList"); 

     chkList.Checked += delegate { SetSelectedItemText(); }; 
    } 

    public CheckBox GetChildObject(DependencyObject obj, string name) 
    { 
     for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) 
     { 
      DependencyObject c = VisualTreeHelper.GetChild(obj, i); 
      if (c.GetType().Equals(typeof(CheckBox)) && (String.IsNullOrEmpty(name) || ((FrameworkElement)c).Name == name)) 
      { 
       return (CheckBox)c; 
      } 
      DependencyObject gc = GetChildObject(c, name); 
      if (gc != null) 
       return (CheckBox)gc; 
     } 
     return null; 
    } 

을 해고되지 않는 이유는 무엇입니까? 도와주세요

답변

1

ItemTemplateDataTemplate 인 이유를 알아야합니다. 목록 상자에 표시해야하는 각 항목에 대해 LoadContent() 메서드가 호출됩니다. 이 경우 설명 된 내용의 새 인스턴스가 만들어지며 여기에는 새 확인란이 포함됩니다. 이 모든 것은 ListBoxItem의 내용으로 할당 될 때 항목에 바인딩됩니다.

이 경우 확인란의 모든 인스턴스는 독립적 인 개체입니다. 당신이 한 모든 것은 실제 UI에서 아무데도 사용되지 않고 이벤트 처리기를 첨부 한 또 다른 독립적 인 인스턴스를 만들었습니다. 목록의 항목에 대한 확인란 중이 핸들러를 공유하지 않으므로 이벤트 코드가 호출되지 않습니다. ItemTemplate을을

+0

답장을 보내 주셔서 감사에 대한 문제를 해결 아래 코드

 var checkBox = new CheckBox { DataContext = item }; if (string.IsNullOrEmpty(TextContent)) checkBox.Content = item.ToString(); else checkBox.SetBinding(ContentControl.ContentProperty, new Binding(TextContent) { Mode = BindingMode.OneWay }); if (!string.IsNullOrEmpty(BindValue)) checkBox.SetBinding(ToggleButton.IsCheckedProperty, new Binding(BindValue) { Mode = BindingMode.TwoWay }); checkBox.SetBinding(IsEnabledProperty, new Binding("IsEnabled") { Mode = BindingMode.OneWay }); checkBox.Checked += (sender, RoutedEventArgs) => { SetSelectedItemText(true, ((CheckBox)sender).GetValue(CheckBox.ContentProperty).ToString()); }; checkBox.Unchecked += (sender, RoutedEventArgs) => { SetSelectedItemText(true, ((CheckBox)sender).GetValue(CheckBox.ContentProperty).ToString()); }; 

을 추가했다. 그러나 체크 된 이벤트를 어떻게 처리 할 수 ​​있습니까? – Bhaskar