Silverlight的3.0自定义列表框DataTemplate中都有一个复选框,选中事件不触发
-
26-09-2019 - |
题
为列表框的DataTemplate中被动态地由XamlReader.Load设置。我通过获取使用VisualTreeHelper.GetChild将CheckBox对象订阅经过事件。此事件不被解雇
代码段
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;
}
如何办理托运事件?请大家帮忙
解决方案 2
删除的ItemTemplate并加入下面的代码
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()); };
这解决了该问题
其他提示
您需要理解为什么ItemTemplate
是DataTemplate
的原因。对于每个项目的列表框中需要显示它会调用LoadContent()方法。此创建内容的新实例描述包括,在这种情况下,一个新的复选框。所有这然后获取绑定到当它被指定为一个ListBoxItem的内容的项目。
所有在此情况下复选框的情况下是独立的对象。所有你做的是创造又未实际UI的任何地方使用和连接的事件处理程序,以它的另一个独立的实例。的复选框在列表中的项目中没有将共享这个处理程序,因此该事件的代码没有被调用。
不隶属于 StackOverflow