我维护了逆布尔值转换器,以通过单选按钮绑定bool属性。第一次正常工作。在使用窗口的数据上下文再次设置模型属性的相同实例时,我得到了堆栈溢出异常。
C#:
public partial class Launcher : Window,INotifyPropertyChanged
{
public Launcher()
{
InitializeComponent();
}
bool test;
public bool Test
{
get
{
return test;
}
set
{
test = value;
RaiseEvent("Test");
}
}
void RaiseEvent(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
private void Button_Click(object sender, RoutedEventArgs e)
{//
On first button click its work normally after close the mainwindow again click the same
button to launch the Mainwindow.
Window obj = new MainWindow();
obj.DataContext = this;
obj.ShowDialog();
}
}
public class InverseBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is bool && (bool)value ? false : true;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool)
{
return !(bool)value;
}
return value;
}
}
XAML:
<Window.Resources>
<local:InverseBoolConverter x:Key="inverse"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<RadioButton Content="A" IsChecked="{Binding Test,Converter={StaticResource inverse}}" GroupName="A"/>
<RadioButton Content="B" Grid.Row="1" IsChecked="{Binding Test}" GroupName="A"/>
</Grid>
查看共享代码,该按钮上的click事件用于激活主窗口。在这种情况下,第二次单击将多次触发转换回,最终结果是异常。