简体   繁体   English

WPF - MVVM - 更改 VM 实例的属性时视图不会更新

[英]WPF - MVVM - View doesn't update when changing properties of a VM instance

I'm fairly new to MVVM and WPF so take everything what I'm saying with a grain of salt.我对 MVVM 和 WPF 还很陌生,所以对我所说的一切持保留态度。 My problem is quite complex and I've been trying to find a solution for the past day now.我的问题非常复杂,过去一天我一直在努力寻找解决方案。 To no avail...无济于事...

Context语境

I'm trying to make a POS system by myself.我正在尝试自己制作一个POS系统。 Everything was going according to plan.一切都按计划进行。 Until this: When there's a barcode being scanned that's too short I open up a small view that asks for the size and color-code of the article.直到:当扫描的条形码太短时,我会打开一个小视图,询问文章的尺寸和颜色代码。 This is done via an ICommand.这是通过 ICommand 完成的。

I can make an article and add it to my ObservableCollection.我可以写一篇文章并将其添加到我的 ObservableCollection 中。 I access this observable collection with the instance I created off the ViewModel.我使用从 ViewModel 创建的实例访问这个可观察的集合。

But now the weird thing happens, I update a "total" texblock and a "amount" textblock as well.但是现在奇怪的事情发生了,我更新了一个“总”文本块和一个“数量”文本块。 These changes go through and I can see the properties being filled and my OnPropertyChanged is being triggered but there's nothing to see on the view.通过这些更改 go ,我可以看到属性正在填充并且我的 OnPropertyChanged 正在被触发,但视图上没有任何内容可看。 The weird thing is that my ObservableCollection is changing but my textboxes aren't.奇怪的是我的 ObservableCollection 正在改变,但我的文本框没有。 I'm pretty convinced there's nothing going wrong with my ICommand because I can create the actual article and add it to my cart.我非常确信我的 ICommand 没有任何问题,因为我可以创建实际文章并将其添加到我的购物车中。 I've been trying to debug for a while now and I can see that it's going through the setter of my properties with the correct value.我一直在尝试调试一段时间,我可以看到它正在以正确的值通过我的属性的设置器。 And the weird part is, if I added an article like that the textblock's will be wrong but when I add a new article in another way (via the original VM - not a new window) it takes the correct total and amount.奇怪的是,如果我添加了这样的文章,文本块将是错误的,但是当我以另一种方式(通过原始 VM - 不是新窗口)添加新文章时,它需要正确的总数和数量。 It's like my view doesn't want to update and I have no clue on how I can force it to update.就像我的视图不想更新,我不知道如何强制它更新。

I've been trying to find a way to make everything work and hopefully somebody can give me an insight on what I'm doing wrong because I'm pretty much clueless: :D我一直在努力寻找一种让一切正常的方法,希望有人可以让我了解我做错了什么,因为我几乎一无所知::D

There might be typing errors or stuff like that in the code below but I'm quite sure you can ignore the most basic stuff.下面的代码中可能存在输入错误或类似的内容,但我很确定您可以忽略最基本的内容。 I'm implementing everything, the change is going through it's just NOT SHOWING UP.我正在实施一切,改变正在经历它只是没有出现。

Code代码

Example property that is refusing to show up after changing it:更改后拒绝显示的示例属性:

(these properties are inside my main VM) (这些属性在我的主虚拟机中)

private static string _totalstr { get; set; }
    public string TotalStr
    {
        get { return _totalstr; }
        set
        {
            _totalstr = value;
            OnPropertyChanged(nameof(TotalStr));
        }
    }

Cart that is showing changes after I add an article添加文章后显示更改的购物车

private static ObservableCollection<Art> _cart;
    public ObservableCollection<Art> Cart
    {
        get
        {
            return _cart;
        }
        set
        {
            _cart = value;
            OnPropertyChanged(nameof(Cart));

        }
    }

Asking for size - VM询问大小 - VM

This is a small version because there's more than that happening but this is the gist of it.这是一个小版本,因为发生的不止这些,但这就是它的要点。 There's parts in my native language as well so I tried translating to the best of my abilities.我的母语也有部分内容,所以我尽力翻译。

public ICommand SizeColorCommand { get; set; }
public SizeColorViewModel()
        {
            this.SizeColorCommand = new SizeColorCommand(this);
        }

    public void function(object parameter)
    {
        MainViewModel.Instance.Cart.Add(artikel);
        MainViewModel.Instance.Total += (double)article.EVkp;
        MainViewModel.Amount++;
        MainViewModel.Instance.TotaalStr = String.Format("{0:c}", MainViewModel.Instance.Total);
    }
                

Size Color Command大小颜色命令

class SizeColorCommand: ICommand
{
    public SizeColorViewModel VM { get; set; }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public SizeColorCommand(SizeColorViewModel vm)
    {
        VM = vm;
    }

    public bool CanExecute(object parameter)
    {
        string query = parameter as string;

        if (string.IsNullOrWhiteSpace(query))
            return false;
        return true;
    }

    public void Execute(object parameter)
    {
        VM.function(parameter);
    }
}

Asking for size - XAML询问尺寸 - XAML

            <TextBox>
                <TextBox.InputBindings>
                    <KeyBinding Key="Enter" Command="{Binding SizeColorCommand}" CommandParameter="{Binding Path=Text, RelativeSource={RelativeSource AncestorType={x:Type TextBox}}}" />
                </TextBox.InputBindings>
            </TextBox>

MainVM - XAML MainVM - XAML

            <TextBlock Text="{Binding TotalStr, Mode=TwoWay}"/>

Screenshot#截屏#

picture of the POS, it's in Dutch so sorry in advance, Stuks/Aantal = AMOUNT POS 的图片,它是荷兰语,所以提前抱歉,Stuks/Aantal = AMOUNT

Thank you so much if you've come this far to try and help me.非常感谢你能走这么远来帮助我。 I hope I can learn and fix this issue.我希望我可以学习并解决这个问题。 I've read a lot this afternoon and singleton might not be the best thing to do but I can't seem to think of a better way.我今天下午读了很多书,singleton 可能不是最好的选择,但我似乎想不出更好的方法。

  1. Ensure that MainViewModel.Instance is the DataContext of your MainWindow.确保 MainViewModel.Instance 是 MainWindow 的 DataContext。 The easiest way to do this is by specifying the attribute: DataContext="{x:Static local:MainViewModel.Instance}"最简单的方法是指定属性: DataContext="{x:Static local:MainViewModel.Instance}"

  2. You need to specify your TextBox.Text bindings as {Binding PropertyName, Mode=TwoWay} .您需要将TextBox.Text绑定指定为{Binding PropertyName, Mode=TwoWay}

Edit:编辑:

If Cart is being exposed in the UI via a ListBox or a ComboBox, you can also specify that the TextBoxes should use their selected value as a reference point for the Binding like this: Text="{Binding ElementName=nameOfTextBoxInXAML, Path=SelectedItem.PropertyOnSelectedValue"如果通过 ListBox 或 ComboBox 在 UI 中公开Cart ,您还可以指定 TextBox 应使用其选定值作为绑定的参考点,如下所示: Text="{Binding ElementName=nameOfTextBoxInXAML, Path=SelectedItem.PropertyOnSelectedValue"

Using this syntax ensures that your TextBoxes always work with the values of the selected item.使用此语法可确保您的文本框始终使用所选项目的值。

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

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