IConverter C#,wpf ,checkbox.Checked
本文关键字:Checked checkbox wpf IConverter | 更新日期: 2023-09-27 18:11:52
XAML Code
<TreeView.Resources>
<local:BoolToVisibleOrHidden x:Key="BoolToVisConverter" Collapse="True"/>
</TreeView.Resources>
<TreeViewItem Header="First Child" Name="_firstChild"
Visibility="{Binding Path=VisibleOnCheck, Mode=OneWay, NotifyOnTargetUpdated=True, Converter={StaticResource BoolToVisConverter}}" />
<CheckBox Name="_checkBoxvisible" IsChecked="{Binding Path= VisibleOnCheck, Mode=TwoWay}" Content="show" Checked="CheckBox />
复选框选中
private void CheckBox(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("", "", MessageBoxButton.YesNo) ==
System.Windows.Forms.DialogResult.Yes)
{
VisibleOnCheck = true;
}
else
{
VisibleOnCheck = false;
}
}
模型代码
Private bool __visible;
public bool VisibleOnCheck
{
get { return _ visible; }
set { _visible = value; OnPropertyChanged("VisibleOnCheck "); }
}
public class BoolToVisibleOrHidden : IValueConverter
{
#region Constructors
public BoolToVisibleOrHidden() { }
#endregion
#region Propertie Collapse
public bool Collapse { get; set; }
public bool Reverse { get; set; }
#endregion
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool bValue = (bool)value;
if (bValue != Reverse)
{
return Visibility.Visible;
}
else
{
if (Collapse)
return Visibility.Collapsed;
else
return Visibility.Hidden;
}
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
Visibility visibility = (Visibility) value;
if (visibility == Visibility.Visible)
return !Reverse;
else
return Reverse;
}
#endregion
}
我想,当MessageBox . yes点击时,Treeview项目头应该是可见的,但这里是可见的MessageBox和TreeviewItem同时没有点击MessageBox。是的,有谁能帮忙吗?
复选框上有一个双向绑定到VisibleOnCheck
,所以如果你选中了Checkbox
,它将在TreeViewItem
上切换Visibility
。
如果你想在基于DialogResult
的Checked事件处理程序中处理VisibleOnCheck
,你必须删除双向绑定或完全删除绑定。
<CheckBox Name="_checkBoxvisible" Content="show" Checked="CheckBox />
我还建议使用WPF
MessageBox
而不是Winforms
,为MessageBox
拖入另一个框架似乎有点奇怪。
private void CheckBox(object sender, RoutedEventArgs e)
{
VisibleOnCheck = MessageBox.Show("","", MessageBoxButton.YesNo) == MessageBoxResult.Yes;
}
编辑
由于问题是由于两个控件绑定到VisibleOnCheck
,你可以直接绑定TreeViewItem
Visibility
到Xaml
中的Checkbox
<TextBlock Text="TreeViewItem" Visibility="{Binding IsChecked, ElementName=chkbx, Converter={StaticResource BooleanToVisibilityConverter}}" />
<CheckBox x:Name="chkbx" Content="CheckBox" Checked="Checked" />
和在事件中设置IsChecked
基于你的对话结果
private void Checked(object sender, RoutedEventArgs e)
{
(sender as CheckBox).IsChecked = MessageBox.Show("","", MessageBoxButton.YesNo) == MessageBoxResult.Yes;
}