簡體   English   中英

綁定到對象本身,當單個屬性更改時不會更新

[英]Binding to object itself, doesn't update when individual property changes

在列表框中,我有一個具有許多屬性的對象列表,並且由於我一次渲染所有對象並且對象是通用的,因此我綁定到對象本身。

<local:ItemRenderer ItemReference="{Binding Path=."}/>

問題是當底層對象更新其中一個屬性時, OnPropertyChanged不會觸發綁定更新。 有沒有辦法在任何屬性更改時觸發綁定更新?

一個想法是擁有一個僅用於通知的屬性,但底層的ObservableCollection是 Object 類型,添加BindingNotifier="{Binding Path=BindingNotifier"}無法識別並且不起作用。

編輯

這似乎是一個很好的解決方案,但它不起作用

public class MyObject : INotifyPropertyChanged {
    public MyObject Self
    {
        get { return this; }            
    }

然后我嘗試綁定

<local:ItemRenderer ItemReference="{Binding Self"}/>

這適用於初始綁定,但調用

OnPropertyChanged("Self");

不更新對象。

根據需要將控件或視圖或頁面或所有內容的數據上下文重置為null然后將其交換回最近更改的實例。 將其更改為相同的引用不起作用...需要兩個步驟


以下是實際代碼,在類似情況下,由於命令(從 VM 執行以保持 VM 和視圖操作分開)的更改,我需要以相同的方式觸發控件以更新視圖控件。

在下面的代碼中發生了相同的情況,其中通知更改的單個屬性沒有更新CurrentBatch上的整個實例綁定。 其他控件必須更新以表示有關CurrentBatch某些內容CurrentBatch變化......

public MainWindow()
{
    DataContext = VM = new CertifyingVM();

    VM.CommandRefreshBindings = new OperationCommand(o =>
    {
        MainAccessionHeader.DataContext =
        MainHeader.DataContext = null;

        MainAccessionHeader.DataContext =
        MainHeader.DataContext = VM;

        var currentBatch = VM.CurrentBatch;
        MainAccessionHeader.CurrentBatch = null;
        MainAccessionHeader.CurrentBatch = currentBatch;

    });

    VM.LockBatchGui = new OperationCommand(o =>
    { ... }

OperationCommand是我的ICommand操作,在我的博客文章Xaml: MVVM Example for Easier Binding 中進行了演示。

您如何觸發它取決於您,只需將 datacontext 的值刪除為 null 然后將其設置回來。

您可以使用IMultiValueConverter實現並綁定到對象本身和在對象的任何屬性更改時都會更改的屬性:

public class TheConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values[0]; //return the actual object
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

XAML:

<local:ItemRenderer>
    <local:ItemRendered.ItemsReference>
        <MultiBinding>
            <MultiBinding.Converter>
                <local:TheConverter />
            </MultiBinding.Converter>
            <Binding Path="." />
            <Binding Path="BindingNotifier" />
        </MultiBinding>
    </local:ItemRendered.ItemsReference>
</local:ItemRenderer>

這要求您在修改對象的任何屬性時設置BindingNotifier屬性。 另一種選擇是為每個屬性添加一個<Binding>元素。

暫無
暫無

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

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