【问题标题】:C# WPF DataContext and unsuccessful bindingC# WPF DataContext 和不成功的绑定
【发布时间】:2018-10-16 03:39:12
【问题描述】:

我在用户控件中使用 DataGrid,并尝试将其绑定到 ViewModel 中的 ObservalbeCollection。

我尝试了很多东西,但是数据在添加时没有显示在 DataGrid 中,只有标题。

ObservavleCollection 属于“LogItem”类型:

namespace Gui
{
    public class LogItem
    {
        public String Type { get; set; }
        public String Message { get; set; }

        public LogItem(string Type, string Message)
        {
            this.Type = Type;
            this.Message = Message;
        }
    }
}

ViewNodel,包含 ObservavleCollection。

namespace Gui.vm
{
    public class LogVm:INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;
        #region properties
        private ObservableCollection<LogItem> logsCollection;
        public ObservableCollection<LogItem> LogsCollection
        {
            get { return this.logsCollection; }
            set => throw new NotImplementedException();
        }
        #endregion

        #region members
        private LogModel model;
        #endregion

        public LogVm()
        {
            Debug.Print("in logVm ctor");
            this.model = new LogModel();
            this.logsCollection = new ObservableCollection<LogItem>
            {
                // For testing
                new LogItem("INFO", "bla"),
                new LogItem("INFO", "bla"),
                new LogItem("INFO", "bla"),
                new LogItem("INFO", "bla")
            };
        }
    }
}

文件Log.xaml.cs,在这里我将DataContext初始化为LogVm

namespace Gui.views
{
    /// <summary>
    /// Interaction logic for Log.xaml
    /// </summary>
    public partial class Log : UserControl
    {
        public Log()
        {
            InitializeComponent();
            this.DataContext = new LogVm();
        }
}
}

文件Log.xaml

<UserControl x:Class="Gui.views.Log"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Gui.vm"
             mc:Ignorable="d"
             xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
             d:DesignHeight="450" d:DesignWidth="800"
             >

    <Grid>
        <DataGrid x:Name="dgrid" ItemsSource="{ Binding LogsCollection , diag:PresentationTraceSources.TraceLevel=Low}" AutoGenerateColumns="False" CanUserAddRows="False"
                  HorizontalAlignment="Stretch" VerticalAlignment="Stretch">

            <DataGrid.Columns>

                <DataGridTextColumn Header="Type" Width="1*" Binding="{Binding Type ,  diag:PresentationTraceSources.TraceLevel=High}">
                </DataGridTextColumn>

                <DataGridTextColumn Header="Message" Width="9*" Binding="{Binding Message ,  diag:PresentationTraceSources.TraceLevel=Low}">
                </DataGridTextColumn>

            </DataGrid.Columns>
        </DataGrid>
    </Grid>

</UserControl>

我在 XAML 中添加了以下行,用于诊断。

xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"

从第 6 行开始。DataContext 反复显示为 null,即使我在代码中将其设置为 LogVm。

我试图颠倒 initializeComponents() 和数据上下文分配的顺序,但这会导致绑定停用。

'Gui.exe' (CLR v4.0.30319: Gui.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\mscorlib.resources\v4.0_4.0.0.0_he_b77a5c561934e089\mscorlib.resources.dll'. Module was built without symbols.
'Gui.exe' (CLR v4.0.30319: Gui.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework.Aero2\v4.0_4.0.0.0__31bf3856ad364e35\PresentationFramework.Aero2.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
System.Windows.Data Warning: 62 : BindingExpression (hash=64879470): Attach to System.Windows.Controls.DataGrid.ItemsSource (hash=7358688)
System.Windows.Data Warning: 67 : BindingExpression (hash=64879470): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=64879470): Found data context element: DataGrid (hash=7358688) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=64879470): DataContext is null
System.Windows.Data Warning: 65 : BindingExpression (hash=64879470): Resolve source deferred
'Gui.exe' (CLR v4.0.30319: Gui.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework.resources\v4.0_4.0.0.0_he_31bf3856ad364e35\PresentationFramework.resources.dll'. Module was built without symbols.
in logVm ctor
in logModel ctor
in logModel ctor AGAIN
'Gui.exe' (CLR v4.0.30319: Gui.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework-SystemXml\v4.0_4.0.0.0__b77a5c561934e089\PresentationFramework-SystemXml.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Gui.exe' (CLR v4.0.30319: Gui.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\UIAutomationTypes\v4.0_4.0.0.0__31bf3856ad364e35\UIAutomationTypes.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Gui.exe' (CLR v4.0.30319: Gui.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\PresentationCore.resources\v4.0_4.0.0.0_he_31bf3856ad364e35\PresentationCore.resources.dll'. Module was built without symbols.
System.Windows.Data Warning: 67 : BindingExpression (hash=64879470): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=64879470): Found data context element: DataGrid (hash=7358688) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=64879470): DataContext is null
'Gui.exe' (CLR v4.0.30319: Gui.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework-SystemCore\v4.0_4.0.0.0__b77a5c561934e089\PresentationFramework-SystemCore.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
System.Windows.Data Error: 40 : BindingExpression path error: 'Log' property not found on 'object' ''MainWindow' (Name='')'. BindingExpression:Path=Log; DataItem='MainWindow' (Name=''); target element is 'Log' (Name=''); target property is 'DataContext' (type 'Object')
System.Windows.Data Warning: 67 : BindingExpression (hash=64879470): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=64879470): Found data context element: DataGrid (hash=7358688) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=64879470): DataContext is null
'Gui.exe' (CLR v4.0.30319: Gui.exe): Loaded 'C:\Users\avn\AppData\Local\Temp\VisualStudio.XamlDiagnostics.14340\Microsoft.VisualStudio.DesignTools.WpfTap.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Gui.exe' (CLR v4.0.30319: Gui.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Gui.exe' (CLR v4.0.30319: Gui.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\SMDiagnostics\v4.0_4.0.0.0__b77a5c561934e089\SMDiagnostics.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Gui.exe' (CLR v4.0.30319: Gui.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Internals\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Internals.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
System.Windows.Data Warning: 67 : BindingExpression (hash=64879470): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=64879470): Found data context element: DataGrid (hash=7358688) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=64879470): DataContext is null
System.Windows.Data Warning: 67 : BindingExpression (hash=64879470): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=64879470): Found data context element: DataGrid (hash=7358688) (OK)
System.Windows.Data Warning: 71 : BindingExpression (hash=64879470): DataContext is null
System.Windows.Data Warning: 67 : BindingExpression (hash=64879470): Resolving source  (last chance)
System.Windows.Data Warning: 70 : BindingExpression (hash=64879470): Found data context element: DataGrid (hash=7358688) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=64879470): Activate with root item <null>
'Gui.exe' (CLR v4.0.30319: Gui.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization.resources\v4.0_4.0.0.0_he_b77a5c561934e089\System.Runtime.Serialization.resources.dll'. Module was built without symbols.
'Gui.exe' (CLR v4.0.30319: Gui.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\UIAutomationProvider\v4.0_4.0.0.0__31bf3856ad364e35\UIAutomationProvider.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
The program '[14340] Gui.exe' has exited with code 0 (0x0).

我想弄清楚这里出了什么问题很长时间了。

【问题讨论】:

  • 不测试这个尝试将绑定模式设置为单向,因为你让它在 LogsCollection 的设置器中抛出异常。
  • 已添加,但与绑定失败无关。
  • 不确定并认为您会看到该异常,但值得添加,因为无论如何您都有该异常。
  • 你试过放置 this.DataContext = new LogVm();在 InitializeComponent();? 之前
  • @Firas 我试过了,甚至写有问题。它导致绑定停用,并且没有显示任何内容。

标签: c# wpf xaml binding datagrid


【解决方案1】:

两种方式绑定可以提供帮助:

Binding="{Binding Type , Mode=TwoWay}

【讨论】:

  • 之前试过了,没用。
【解决方案2】:

首先,您必须在要从 GUI 更改的属性的设置器中调用 onPropertyChanged()。在你的情况下 - ObservableCollection。

但我认为主要的问题是,当你在 XAML 中定义列时,你应该使用 fieldName,所以你可以试试这个:

<DataGridTextColumn Header="Type" Width="1*" FieldName="Type">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-31
    • 2012-11-05
    • 2021-07-19
    • 2013-02-02
    • 2011-01-23
    • 2012-12-25
    • 2013-11-16
    • 2011-07-07
    相关资源
    最近更新 更多