簡體   English   中英

WPF CheckBox在禁用和啟用后面的代碼后檢查不起作用

[英]WPF CheckBox Check not working after disabling and enabling in code behind

我有ComboBox並基於CheckBox啟用它。 如果我在后面的代碼中禁用並啟用復選框,則它將停止工作。 但是,如果我不這樣做,則在選中復選框時會啟用ComboBox,並在取消選中該復選框時禁用它。

代碼示例如下:

<CheckBox x:Name="ckBox1" IsChecked="{Binding proceed, TargetNullValue=false}" Content="Proceed" FontSize="16"/>

ComboxBox:

<ComboBox x:Name="cmbOptions" SelectedValuePath="Content" SelectedValue="{Binding selOptions}" Width="89" IsEnabled="{Binding IsChecked, ElementName=ckBox1}" >
                                        <ComboBoxItem Content="Option 1"/>
                                        <ComboBoxItem Content="Option 2"/>
                                        <ComboBoxItem Content="Option 3"/>
                                        <ComboBoxItem Content="Other"/>
                                    </ComboBox>

Diabling:

var controls = this.sourceGrid.Children.OfType<Control>();
controls.ToList().ForEach(c => c.IsEnabled = false);

啟用:

controls.ToList().ForEach(c => c.IsEnabled = true);

好吧,這不是一個漂亮的解決方案,但它應該讓你做你需要的。 基本上,在將IsEnabled設置為false之前,您需要獲取對現有Binding對象的引用。 然后在將IsEnabled設置為false或返回true后,重置綁定。 我在Loaded事件處理程序中設置的完整代碼,但只需移動到您需要的地方。

this.Loaded += (s, e) =>
    {
        var controls = this.sourceGrid.Children.OfType<Control>();
        controls.ToList().ForEach(c =>
        {
            ComboBox combo = c as ComboBox;
            Binding newBinding = null;
            if (combo != null)
            {
                newBinding = BindingOperations.GetBinding(combo, ComboBox.IsEnabledProperty);
            }

            c.IsEnabled = false;

            if (combo != null)
            {
                BindingOperations.SetBinding(combo, ComboBox.IsEnabledProperty, newBinding);
            }
        });

        controls.ToList().ForEach(c =>
        {
            ComboBox combo = c as ComboBox;
            Binding newBinding = null;
            if (combo != null)
            {
                newBinding = BindingOperations.GetBinding(combo, ComboBox.IsEnabledProperty);
            }

            c.IsEnabled = true;

            if (combo != null)
            {
                BindingOperations.SetBinding(combo, ComboBox.IsEnabledProperty, newBinding);
            }
        });
    };

我必須強調,這段代碼並不是那么漂亮,請根據您自己的實現進行正確的重構。

您不需要任何代碼隱藏來禁用和啟用您的控件。 在XAML中完成。

<Checkbox x:Name="enablingCheckBox" Content="Enabled?" IsChecked="{Binding IsEnabled}"/>
<Grid IsEnabled="{Binding IsEnabled, Mode=OneWay, ElementName=enablingCheckBox}">
    <Button Content="Sample"/>
    <ComboBox/>
</Grid>

將網格中的IsEnabled屬性設置為false自動禁用屬於該網格的所有控件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM