简体   繁体   English

为什么可观察集合为 xaml 数据绑定提供空值 c# wpf

[英]Why observable collection providing null value to xaml data binding c# wpf

I have a datagrid which need to represent two types of dataset at two different times of event.我有一个数据网格,它需要在两个不同的事件时间表示两种类型的数据集。

  1. On form loading - the datagrid show modelclasswithcombobox (This works fine)在表单加载时 - 数据网格显示模型类和组合框(这很好用)

  2. on button click - the datagrid show modelforseperateusers (The problem is here it shows empty datagrid eventhough the data is populated in collection)单击按钮时 - 数据网格显示模型为单独用户(问题是这里显示空数据网格,即使数据已填充到集合中)

XAML: XAML:

<DataGrid  Height="150" x:Name="datagrid1" AutoGenerateColumns="True" CanUserAddRows="False" Width="467" Margin="299,-135,40,9" HorizontalAlignment="Left">
    <DataGrid.Style>
        <Style  TargetType="{x:Type DataGrid}">
            <Setter  Property="ItemsSource" Value="{Binding Populatedatagridwithobservablecollection.modelclasswithcombobox}"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Isauditorsearch}" Value="True">
                    <Setter Property="ItemsSource" Value="{Binding 
     modelforseperateusers,
     diag:PresentationTraceSources.TraceLevel=High,Mode=TwoWay }"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Style>
</DataGrid>

code:代码:

  public interface INofificationActionfordatagrid {
ObservableCollection < datagridmodel > modelclasswithcombobox {
    get;
    set;
}
void getdatausinglinq();
}

public class PopulateDatagrid: INofificationActionfordatagrid {
public ObservableCollection < datagridmodel > modelclasswithcombobox {
    get;
    set;
}
   public void getdatausinglinq() {
    using(Operations_Productivity_ToolEntities context = new 
 Operations_Productivity_ToolEntities()) {
        var a1 = from t1 in context.Test_ImportedAuditdata
        where t1.status == "Pending"
        select t1;

        if (modelclasswithcombobox == null) modelclasswithcombobox = new 
  ObservableCollection < datagridmodel > ();

        foreach(var a in a1) {
            modelclasswithcombobox.Add(new datagridmodel {

                AuditId = a.AuditId.ToString(),
                Claimnumber = a.ClaimNumber.ToString(),
                UserName = a.username,
                CreateDate = a.Created_Date.ToString(),
                ID = a.id.ToString(),
                Status = a.status

            });
        }
        context.SaveChanges();

    }
    }
 }

public class ViewModel {
public ObservableCollection < datagridmodelforSeperateUsers > 
modelforseperateusers {
    get;
    set;
}

INofificationActionfordatagrid
_populatedatagridwithobservablecollection = new PopulateDatagrid();

public ViewModel() {
    Isauditorsearch = false;
    _populatedatagridwithobservablecollection.getdatausinglinq();
    ReassignusersSeperately = new RelayCommand(o = 
   >Filterbind(Currentcomboboxitem3));
}

public INofificationActionfordatagrid
Populatedatagridwithobservablecollection {
    get {
        return _populatedatagridwithobservablecollection;
    }
    set {
        if (value != _populatedatagridwithobservablecollection) {
            _populatedatagridwithobservablecollection = value;

            OnPropertyChanged("Populatedatagridwithobservablecollection");
        }
    }
   }

   public void Filterbind(string an) {
    Isauditorsearch = true;

    using(Operations_Productivity_ToolEntities context = new 
   Operations_Productivity_ToolEntities()) {
        var a1 = from t1 in context.Test_ImportedAuditdata
        where t1.username == an
        select t1;
        try {
            if (modelforseperateusers == null) modelforseperateusers = new 
     ObservableCollection < datagridmodelforSeperateUsers > ();

            foreach(var a in a1) {
                modelforseperateusers.Add(new 
        datagridmodelforSeperateUsers {
                    toUpdate = false,
                    AuditId = a.AuditId.ToString(),
                    Claimnumber = a.ClaimNumber.ToString(),
                    UserName = a.username,
                    CreateDate = a.Created_Date.ToString(),
                    ID = a.id.ToString(),
                    Status = a.status

                });
            }
            context.SaveChanges();
        } catch(Exception e) {
            MessageBox.Show(e.ToString());
        }
    }
}
}

Problem : The observable collection modelforseperateusers is populated with the data in the viewmodel but it is not binded with the xaml.问题:可观察集合模型为单独用户填充了视图模型中的数据,但未与 xaml 绑定。

On debugging the xaml :在调试 xaml 时:

     Warning: 56 : Created BindingExpression (hash=36729282) for Binding (hash=25749409)
     System.Windows.Data Warning: 58 :   Path: 'modelforseperateusers'
     System.Windows.Data Warning: 61 : BindingExpression (hash=36729282): Default update trigger resolved to PropertyChanged
     System.Windows.Data Warning: 62 : BindingExpression (hash=36729282): Attach to System.Windows.Controls.DataGrid.ItemsSource (hash=55797203)
     System.Windows.Data Warning: 67 : BindingExpression (hash=36729282): Resolving source 
     System.Windows.Data Warning: 70 : BindingExpression (hash=36729282): Found data context element: DataGrid (hash=55797203) (OK)
     System.Windows.Data Warning: 78 : BindingExpression (hash=36729282): Activate with root item ViewModel (hash=38471091)
     System.Windows.Data Warning: 107 : BindingExpression (hash=36729282):   At level 0 using cached accessor for ViewModel.modelforseperateusers: RuntimePropertyInfo(modelforseperateusers)
     System.Windows.Data Warning: 104 : BindingExpression (hash=36729282): Replace item at level 0 with ViewModel (hash=38471091), using accessor RuntimePropertyInfo(modelforseperateusers)
     System.Windows.Data Warning: 101 : BindingExpression (hash=36729282): GetValue at level 0 from ViewModel (hash=38471091) using RuntimePropertyInfo(modelforseperateusers): <null>
     System.Windows.Data Warning: 80 : BindingExpression (hash=36729282): TransferValue - got raw value <null>
     System.Windows.Data Warning: 84 : BindingExpression (hash=36729282): TransferValue - implicit converter produced <null>
     System.Windows.Data Warning: 89 : BindingExpression (hash=36729282): TransferValue - using final value <null>

On seeing the debug information we can see that the collection is providing null value and I believe that is the reason behind the empty datagrid.在查看调试信息时,我们可以看到集合提供了空值,我相信这是空数据网格背后的原因。 Please provide inputs for the issue.请提供该问题的输入。

I had the same issue with my ObservableCollection and other binding.我的 ObservableCollection 和其他绑定也有同样的问题。 I found out that when the application loads you cannot bind to null object.我发现当应用程序加载时你不能绑定到空对象。

So I now initialize all my binding object and everything is working much better.所以我现在初始化我所有的绑定对象,一切都运行得更好。

private ObservableCollection<RaceObject> _obsRaces = new ObservableCollection<RaceObject>();

        public ObservableCollection<RaceObject> ObsRaces
        {
            get => _obsRaces;
        }

Once the binding is done on an existing object instead of null object, you will be able to do anything you want and the binding will always work.一旦在现有对象而不是空对象上完成绑定,您就可以做任何想做的事情,并且绑定将始终有效。

Besides this applies to DependencyObject kind of ViewModel.除此之外这适用于DependencyObject 类型的ViewModel。 I'm not using INotifiChange.我没有使用 INotifiChange。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM