c # WPF DataContext и неудачное связывание - PullRequest
0 голосов
/ 06 мая 2018

Я использую DataGrid внутри Usercontrol и пытаюсь привязать его к моей ObservalbeCollection во ViewModel. Я пробовал очень много вещей, но данные не отображаются в 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 неоднократно отображается как ноль, хотя я установил его как 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 
    '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).


Попытка выяснить, что здесь не так на самом деле долгое время.

1 Ответ

0 голосов
/ 14 мая 2018

Сначала вы должны вызвать onPropertyChanged () в установщике свойства, которое вы хотите изменить из GUI. В твоем случае - ObservableCollection.

Но главная проблема, которую я считаю, состоит в том, что когда вы определяете столбцы в XAML, вы должны использовать fieldName, поэтому вы можете попробовать это:

<DataGridTextColumn Header="Type" Width="1*" FieldName="Type">
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...