Silverlightの3.0カスタムのListBoxの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