簡體   English   中英

Combobox 值發生變化,但視覺上 SelectedValue 保持不變

[英]Combobox value changes, but visually SelectedValue stays the same

我有一個帶有自定義枚舉的 combobox(只是真/假)。 我有一個 function 檢查條件,如果 SelectedValue 從 false 更改為 true,如果條件錯誤,它將 combobox SelectedValue 更改回 false。 如果您在代碼中檢查它,這會將 SelectedValue 更改為 false,但是當您查看 UI 時,它仍然為 true。

這是 combobox 的 xaml:

<ComboBox x:Name="comboEnabled1" Width="80" Height="26"
                          ItemsSource="{Binding Path=TrueFalseChoices}"
                          SelectedValue="{Binding Path=Enable1, Mode=TwoWay}"/>
            

這是視圖模型

private TrueFalse _enable1 = TrueFalse.False;
    public TrueFalse Enable1
    {
        get { return _enable1; }
        set
        {
            if (_enable1 != value)
            {
                _enable1 = value;
                base.OnPropertyChanged("Enable1");
                OnEnableChanged(EventArgs.Empty);
            }
        }
    }

這是我用來檢查條件的 function

public void HandleEnable(object sender, EventArgs e)
    {
        if(Enable1 == TrueFalse.True)
        {
            if(!connected)
            {
                HandleMessage("Can't enable, not connected");
                Enable1 = TrueFalse.False;
            }
            else if (!_main.CBCheck(_main.cbReason))
            {
                Enable1 = TrueFalse.False;
            }

        }
        Console.WriteLine("Enabled {0}", Enable1);

    }

以為我改變值太快了,但最后一個 Console.Writeline 每次都會產生正確的結果。

任何幫助表示贊賞!

編輯:在這里調用 Handleenable:

protected void OnEnableChanged(EventArgs e)
    {
        EventHandler handler = EnableChanged;
        if (handler != null)
            handler(this, e);
    }

在 ViewModel 函數中:

        EnableChanged += HandleEnable;

在任何其他地方更改 Enable1 都可以正常工作,只是在 HandleEnable function 中出現問題。還嘗試更改 HandleEnable function 中的其他組合框,並且按應有的方式工作。

如果不滿足要求,我建議實際禁用 ComboBox。

但是,如果您堅持在不滿足條件的情況下將 Enable1 恢復為 False,則應通過調度程序正確推送通知。

set
{
    var effectiveValue = condition ? value : TrueFalse.False;
    if (effectiveValue == TrueFalse.False && value == TrueFalse.True)
        System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(
            new Action(() => base.OnPropertyChanged("Enable1"), null));
    //your regular set-code follows here
}

發生這種情況是因為 WPF 已經響應該事件,因此在完成之前忽略后續調用。 因此,一旦當前的通行證完成,您就會立即排隊另一個通行證。

但我仍然建議在有效禁用 ComboBox 時禁用它。 無論您怎么看,從視圖模型訪問調度程序都不好聞。

UPD:如果您的框架是 4.5.1+,您也可以使用{Binding Enable1, Delay=10}解決這個問題。

暫無
暫無

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

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