简体   繁体   中英

TwoWay-Binding does not work

the XAML of my window:

<ListView Grid.Row="0" Name="files">
        <ListView.Resources>
            <DataTemplate x:Key="CheckboxTemplate">
                <CheckBox IsChecked="{Binding Save, Mode=TwoWay}" />
            </DataTemplate>
        </ListView.Resources>
        <ListView.View>
            <GridView AllowsColumnReorder="False">
                <GridViewColumn Header=" " Width="30" CellTemplate="{StaticResource CheckboxTemplate}" />
                <GridViewColumn Header="Datei" DisplayMemberBinding="{Binding File}"/>
            </GridView>
        </ListView.View>
    </ListView>

the constructor of my Window:

IEnumerable<SaveItem> sil = sdl.Select(d => new SaveItem() { Save = true, Document = d });
files.ItemsSource = sil;

and the datastructure i want to display:

public class SaveItem : INotifyPropertyChanged
{
    private bool save;
    public bool Save
    {
        get { return this.save; }

        set
        {
            if (value != this.save)
            {
                this.save = value;
                NotifyPropertyChanged("Save");
            }
        }
    }

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
    public StandardDocument Document { get; set; }
    public string File { get { return Document.Editor.File; } }

    #region INotifyPropertyChanged Member

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

i call the window. The window appears. I uncheck a checkbox of an item of the listview. i click a button. in its event-handler i read out the itemssource of the listview and ... the Save-Property of the Unchecked Item is (in its source) still true!

where is my mistake? why does my sources not get updated if i check/uncheck a checkbox?

You have not set your data context. If you are all in the same class - put something like this in your constructor of the window.

DataContext = this;

I think you need to set the DataContext to the code behind and then for clarity bind to the path.

XAML to set the Window DataContext

  DataContext="{Binding RelativeSource={RelativeSource Self}}"

try converting IEnumerable to list.. it is not suggested to use IEnumerable as item source particularly when item source is evaluated using Linq

List<SaveItem> sil = sdl.Select(d => new SaveItem() { Save = true, Document = d }).ToList<SaveItem>();
files.ItemsSource = sil;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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