简体   繁体   English

当单击dataGridview列时WPF-MVVM中文本框的可见性更改?

[英]when click dataGridview column Visiblity change of a textbox in WPF-MVVM?

I want to make a text Box Visible when clicking a DataGrid Column. 单击“ DataGrid列”时,我想使文本框Visible I use this text box for description of a data Grid column 我使用此文本框描述数据网格列

My two column has grid view (Item and Amount columns) 我的两列都有网格视图(“项目”和“金额”列)

<DataGrid>        
    <DataGrid.Columns>    
        <DataGridTemplateColumn Header="Item" Width="*">
            <DataGridTemplateColumn.CellTemplate>
                <TextBlock Text="{Binding Item}" VerticalAlignment="Center"/>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Amount" Width="*">
            <DataGridTemplateColumn.CellTemplate>
                <TextBlock Text="{Binding Amount}" VerticalAlignment="Center"/>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

I want get the sum of Column [Amount] and show it on a textbox, that is visible only when I click [Amount] Column 我想获取[Amount]列的总和并显示在文本框中,该文本框仅在单击[Amount]列时可见

Please try the next code: 1. Xaml: 请尝试下一个代码:1. Xaml:

<Window x:Class="DataGridSoHelpAttempt.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:dataGridSoHelpAttempt="clr-namespace:DataGridSoHelpAttempt"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    Title="MainWindow" Height="350" Width="525" x:Name="This">
<Window.DataContext>
    <dataGridSoHelpAttempt:MainViewModel/>
</Window.DataContext>
<Grid x:Name="MyGrid">
    <DataGrid x:Name="MyDataGrid" ItemsSource="{Binding DataSource}" AutoGenerateColumns="False">
        <i:Interaction.Behaviors>
            <dataGridSoHelpAttempt:ColumnSelectingBehavior TotalPresenterVisibility="{Binding TotalsVisibility, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
        </i:Interaction.Behaviors>
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
            <DataGridTextColumn Header="Comments" Binding="{Binding Comments}" Width="150"/>
            <DataGridTextColumn Header="Price (click to see total)" Binding="{Binding Price, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Bottom">
        <TextBlock Visibility="{Binding TotalsVisibility, UpdateSourceTrigger=PropertyChanged}">
            <Run Text="Total price:"></Run>
            <Run Text="{Binding TotalValue, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"></Run>
        </TextBlock>
    </StackPanel>
</Grid></Window>

2. View models and models code: 2.查看模型和模型代码:

public class MainViewModel:BaseObservableObject
{
    private Visibility _visibility;
    private ICommand _command;
    private Visibility _totalsVisibility;
    private double _totalValue;

    public MainViewModel()
    {
        Visibility = Visibility.Collapsed;
        TotalsVisibility = Visibility.Collapsed;
        DataSource = new ObservableCollection<BaseData>(new List<BaseData>
        {
            new BaseData {Name = "Uncle Vania", Description = "A.Chekhov, play", Comments = "worth reading", Price = 25},
            new BaseData {Name = "Anna Karenine", Description = "L.Tolstoy, roman", Comments = "worth reading", Price = 35},
            new BaseData {Name = "The Master and Margarita", Description = "M.Bulgakov, novel", Comments = "worth reading", Price = 56},
        });
    }

    public ICommand Command
    {
        get
        {
            return _command ?? (_command = new RelayCommand(VisibilityChangingCommand));
        }
    }

    private void VisibilityChangingCommand()
    {
        Visibility = Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
    }

    public ObservableCollection<BaseData> DataSource { get; set; }

    public Visibility Visibility
    {
        get { return _visibility; }
        set
        {
            _visibility = value;
            OnPropertyChanged();
        }
    }

    public ObservableCollection<BaseData> ColumnCollection
    {
        get { return DataSource; }
    }

    public Visibility TotalsVisibility
    {
        get { return _totalsVisibility; }
        set
        {
            _totalsVisibility = value;
            OnPropertyChanged();
        }
    }

    public double TotalValue
    {
        get { return ColumnCollection.Sum(x => x.Price); }
    }

}

public class BaseData:BaseObservableObject
{
    private string _name;
    private string _description;
    private string _comments;
    private int _price;

    public virtual string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged();
        }
    }

    public virtual object Description
    {
        get { return _description; }
        set
        {
            _description = (string) value;
            OnPropertyChanged();
        }
    }

    public string Comments
    {
        get { return _comments; }
        set
        {
            _comments = value;
            OnPropertyChanged();
        }
    }

    public int Price
    {
        get { return _price; }
        set
        {
            _price = value;
            OnPropertyChanged();
        }
    }
}

3. Behavior code: 3.行为代码:

 public class ColumnSelectingBehavior : Behavior<DataGrid>
{
    public static readonly DependencyProperty TotalPresenterVisibilityProperty = DependencyProperty.Register(
        "TotalPresenterVisibility", typeof (Visibility), typeof (ColumnSelectingBehavior), new PropertyMetadata(Visibility.Collapsed));

    public Visibility TotalPresenterVisibility
    {
        get { return (Visibility) GetValue(TotalPresenterVisibilityProperty); }
        set { SetValue(TotalPresenterVisibilityProperty, value); }
    }

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Sorting += AssociatedObjectOnSorting;
    }

    private void AssociatedObjectOnSorting(object sender, DataGridSortingEventArgs dataGridSortingEventArgs)
    {
        var columnSortMemberPath = dataGridSortingEventArgs.Column.SortMemberPath;
        if(columnSortMemberPath != "Price")
            return;
        TotalPresenterVisibility = TotalPresenterVisibility == Visibility.Visible
            ? Visibility.Collapsed
            : Visibility.Visible;
    }


    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.Sorting -= AssociatedObjectOnSorting;
    }
}

4. BaseObservableObject code (for .net 4.5): 4. BaseObservableObject代码(用于.net 4.5):

    public class BaseObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    protected virtual void OnPropertyChanged<T>(Expression<Func<T>> raiser)
    {
        var propName = ((MemberExpression)raiser.Body).Member.Name;
        OnPropertyChanged(propName);
    }

    protected bool Set<T>(ref T field, T value, [CallerMemberName] string name = null)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            OnPropertyChanged(name);
            return true;
        }
        return false;
    }
}

I'll glad to help in case you will have problems wit the code. 如果您在使用代码时遇到问题,我很乐意提供帮助。 Regards. 问候。

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

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