为什么可观察的集合为XAML数据绑定提供空值C#WPF

时间:2019-04-02 14:23:50

标签: c# wpf data-binding

我有一个数据网格,需要在两个不同的事件时间代表两种类型的数据集。

  1. 在表单加载时-datagrid显示modelclasswithcombobox(这很好)

  2. 单击按钮-datagrid显示适合用户的模型(问题是,即使数据已填充到集合中,它也显示空的datagrid)

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>

代码:

  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());
        }
    }
}
}

问题:可观察用户的集合模型在视图模型中填充了数据,但未与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>

在查看调试信息时,我们可以看到该集合提供了空值,我相信这是空数据网格背后的原因。请提供有关此问题的信息。

1 个答案:

答案 0 :(得分:1)

我的ObservableCollection和其他绑定有相同的问题。 我发现,当应用程序加载时,您无法绑定到空对象。

所以我现在初始化所有绑定对象,并且一切工作都好得多。

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

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

一旦绑定是在现有对象而不是null对象上完成的,则您将能够做任何您想做的事,并且绑定将始终有效。

此外,这适用于DependencyObject类型的ViewModel。我没有使用INotifiChange。