简体   繁体   English

绑定不会更新

[英]Binding wont update

I have strange problem, my Textbox in ListView's DataTemplate wont update its data. 我有一个奇怪的问题,我在ListView的DataTemplate中的文本框不会更新其数据。 Data are setted in my property "LastValue" but it was never return. 数据在我的属性“ LastValue”中设置,但从未返回。

Here is my ViewModel code (only important parts of this class): 这是我的ViewModel代码(仅此类的重要部分):

public interface ISignal : IValue, IChartItem, INotifyPropertyChanged
{
    string SignalName { get; set; }
}

[Serializable]
public class Signal : ObservableObject, ISignal
{
    public Signal()
        : this(new ModelsDialogService())
    {
        LastValue = 0.0;
    }

    public Signal(IDialogService dialog)
    {
        dialogService = dialog;
        VisibleInGraph = true;
        RefreshRate = 1000;
        Include = true;
        Color = ColorList.FirstOrDefault();
        LastValue = 0.0;
    }

    private readonly List<SignalValue> values = new List<SignalValue>();
    [XmlIgnore]
    public IEnumerable<SignalValue> Values
    {
        get
        {
            return values;
        }
    }

    private double lastValue;
    [XmlIgnore]
    public double LastValue
    {
        get
        {
            return lastValue;
        }
        set
        {
            Set(ref lastValue, value);
            //RaisePropertyChanged(() => LastValue);
        }
    }

    public void AddValue(SignalValue val)
    {
        values.Add(val);
        ValueAdded(this, new ValueAddedEventArgs(val));
        LastValue = Convert.ToDouble(((XYValue)val).Value);
    }
}

And my XAML: 而我的XAML:

<ListView ItemsSource="{Binding SignalGroup.Signals}" SelectedValue="{Binding SelectedSignal}" FontWeight="Normal" BorderThickness="0" Foreground="white" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" DockPanel.Dock="Top" Background="#FF5B5A5A" Margin="10" >
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Style.Resources>
                    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                         Color="{StaticResource MetroBlueColor}"/>
                </Style.Resources>
                <Setter Property="ContextMenu">
                    <Setter.Value>
                        <ContextMenu ItemsSource="{Binding CommandList}">
                            <ContextMenu.ItemTemplate >
                                <DataTemplate>
                                    <MenuItem Header="{Binding DisplayName}" Command="{Binding ContextMenuCommand}" />
                                </DataTemplate>
                            </ContextMenu.ItemTemplate>
                        </ContextMenu>
                    </Setter.Value>
                </Setter>
                <Setter Property="HorizontalAlignment" Value="Stretch" />
            </Style>
        </ListView.ItemContainerStyle>
        <ListView.ItemTemplate>
            <DataTemplate>
                <DockPanel HorizontalAlignment="Stretch">
                    <TextBlock Text="{Binding SignalName}" DockPanel.Dock="Left" />
                    <TextBlock Text="{Binding LastValue}" TextAlignment="Right" Margin="10,0,10,0" DockPanel.Dock="Right"/>
                </DockPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

Thanks for any idea. 感谢您的任何想法。

Oh, i found interesting fact. 哦,我发现了一个有趣的事实。 Binding doesn't work only after deserialization. 绑定仅在反序列化之后才起作用。 When I create new structure etc.. it works but when I serialize this structure to XML using XMLSerializer and then deserialize every binding in this class doesen't work, so I can change all values but its not updated in GUI... Weird 当我创建新结构等时,它可以工作,但是当我使用XMLSerializer将该结构序列化为XML,然后反序列化此类中的每个绑定都行不通时,所以我可以更改所有值,但不能在GUI中更新它。

I have implemented a very small MVVM example. 我已经实现了一个非常小的MVVM示例。

Lets assume that the Signal class has only the two attributes you want to bind to. 假设Signal类仅具有要绑定到的两个属性。 Then Signal looks very clean and easy: 然后, Signal看起来非常干净和容易:

public class Signal
{
    public string SignalName { get; set; }

    public double LastValue { get; set; }
}

Obviously Signal is your Model ! 显然, Signal是您的Model

Now you need the ViewModel which has the name name in my small test application: 现在,您需要在我的小型测试应用程序中使用名称为ViewModel

public class ViewModel
{
    public ViewModel()
    {
        this.Signals = new ObservableCollection<Signal>();
        this.Signals.Add(new Signal() { LastValue = 12432.33, SignalName = "First Signal"} );
        this.Signals.Add(new Signal() { LastValue = 2.123, SignalName = "Second Signal"});
    }

    public ObservableCollection<Signal> Signals { get; set; }
}

An ObservableCollection is like a list with the difference that the View is notified when the Collection changes. ObservableCollection就像一个列表,不同之处在于Collection更改时会通知View The collection changes with operations like .Add(...) and .Remove(...) . 集合会随着.Add(...).Remove(...)等操作而变化。

The View looks similar to yours. 视图与您的视图相似。 i have choosen a GridView, because it is much more handy because it supports features like sorting and editing of the elements: 我选择了GridView,因为它更方便,因为它支持元素的排序和编辑等功能:

<DataGrid ItemsSource="{Binding Signals}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="LastName" Binding="{Binding SignalName}" />
        <DataGridTextColumn Header="LastName" Binding="{Binding LastValue}" />
    </DataGrid.Columns>
</DataGrid>

You may want to set the IsReadOnly to True when you are using the GridView A solution with a ListView should look the same! 使用GridView时,可能需要将IsReadOnly设置为True 。使用ListView的解决方案应该看起来一样!

The Result: 结果:
在此处输入图片说明

Make sure, that you use the MVVM Pattern correctly. 确保正确使用MVVM模式。 The Model only holds the data. 该模型仅保存数据。 The ViewModel is for all the business logic and the View only shows the data. ViewModel适用于所有业务逻辑,而View仅显示数据。

I would also recommend to create a folder structure so you have better overview over your solution. 我还建议创建一个文件夹结构,以便您对解决方案有更好的了解。 It also makes it easier to follow the MVVM pattern. 这也使遵循MVVM模式变得更加容易。

在此处输入图片说明

Hope it helps and clarified MVVM 希望它能帮助和澄清MVVM

Thank you for your request, it is really useful, but I´ve found where the problem is. 谢谢您的要求,它确实有用,但是我发现问题出在哪里。

I have two collections in my application. 我的应用程序中有两个集合。 I add Signals to first and when user wants to monitor some of these signals, selected signals are putted to the second collection too(but only its reference). 我先添加Signals,然后当用户想要监视其中的一些信号时,选定的信号也会放入第二个集合(但仅作为参考)。 Serialization creates the XML from this structure and deserialization overlooks the references and creates a new object of signal in first and also second collection. 序列化从该结构创建XML,反序列化忽略引用,并在第一个和第二个集合中创建信号的新对象。 And here we go! 现在我们开始! :-D :-D

I feel really stupid and dumb after dicovering this. 发现这一点后,我感到非常愚蠢和愚蠢。 I must refactor it till I forgot it. 我必须重构它,直到我忘了它。 I spent a lot of time by searching the cause of this bug. 我花了很多时间来查找此错误的原因。

Thank for your request anyway! 仍然感谢您的请求!

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

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