单击“数据网格视图列”时,WPF-MVVM 中文本框的可见性更改

本文关键字:文本 中文 WPF-MVVM 可见性 数据网 数据 网格 视图 单击 | 更新日期: 2023-09-27 18:30:28

我想在单击数据网格列时Visible文本框。我使用此文本框来描述数据网格列

我的两列具有网格视图(项目和金额列)

<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>

我想获取列[Amount]的总和并将其显示在文本框中,该文本框仅在我单击[Amount]列时才可见

单击“数据网格视图列”时,WPF-MVVM 中文本框的可见性更改

请尝试下一个代码: 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. 查看模型和模型代码:

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. 行为守则:

 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(适用于 .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;
    }
}

如果您遇到代码问题,我很乐意为您提供帮助。问候。