Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当单击dataGridview列时,WPF-MVVM中文本框的可见性会发生变化吗?_C#_Wpf_Mvvm_Wpfdatagrid - Fatal编程技术网

C# 当单击dataGridview列时,WPF-MVVM中文本框的可见性会发生变化吗?

C# 当单击dataGridview列时,WPF-MVVM中文本框的可见性会发生变化吗?,c#,wpf,mvvm,wpfdatagrid,C#,Wpf,Mvvm,Wpfdatagrid,我想在单击DataGrid列时使文本框可见。我使用此文本框来描述数据网格列 我的两列有网格视图(项目和金额列) 我想获取列[Amount]的总和,并将其显示在文本框中,该文本框仅在我单击[Amount]列时可见。请尝试下一个代码: 1.Xaml: <Window x:Class="DataGridSoHelpAttempt.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

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

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


我想获取列
[Amount]
的总和,并将其显示在文本框中,该文本框仅在我单击
[Amount]
列时可见。请尝试下一个代码: 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>

二,。查看模型和模型代码:

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();
        }
    }
}
public类MainViewModel:baseObserveObject
{
私人能见度;
专用ICommand_命令;
私人可视性(即总体可视性);;
私人双重价值;
公共主视图模型()
{
可见性=可见性。已折叠;
TotalsVisibility=可见性。已折叠;
数据源=新的ObservableCollection(新列表
{
新的基本数据{Name=“Vania叔叔”,Description=“A.Chekhov,play”,Comments=“worth reading”,Price=25},
新的基础数据{Name=“Anna Karenine”,Description=“L.Tolstoy,roman”,Comments=“worth reading”,Price=35},
新的基本数据{Name=“大师和玛格丽塔”,Description=“M.Bulgakov,小说”,Comments=“值得一读”,Price=56},
});
}
公共ICommand命令
{
得到
{
返回_命令??(_命令=新的RelayCommand(VisibilityChangingCommand));
}
}
私有void VisibilityChangingCommand()
{
可见性=可见性==可见性。折叠?可见性。可见:可见性。折叠;
}
公共ObservableCollection数据源{get;set;}
公众能见度
{
获取{return\u visibility;}
设置
{
_能见度=价值;
OnPropertyChanged();
}
}
公共可观测集合列集合
{
获取{return DataSource;}
}
公众能见度
{
获取{return\u totalsVisibility;}
设置
{
_总体可视性=数值;
OnPropertyChanged();
}
}
公共双重总价值
{
获取{return ColumnCollection.Sum(x=>x.Price);}
}
}
公共类BaseData:BaseObserveObject
{
私有字符串\u名称;
私有字符串描述;
私有字符串注释;
私人国际价格;
公共虚拟字符串名
{
获取{return\u name;}
设置
{
_名称=值;
OnPropertyChanged();
}
}
公共虚拟对象描述
{
获取{return\u description;}
设置
{
_description=(字符串)值;
OnPropertyChanged();
}
}
公共字符串注释
{
获取{return\u comments;}
设置
{
_评论=价值;
OnPropertyChanged();
}
}
公共整数价格
{
获取{return\u price;}
设置
{
_价格=价值;
OnPropertyChanged();
}
}
}
三,。行为准则:

 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;
    }
}
公共类列SelectingBehavior:Behavior
{
公共静态只读DependencyProperty TotalPresenterVisibilityProperty=DependencyProperty.Register(
“TotalPresenterVisibility”、typeof(可见性)、typeof(ColumnSelectingBehavior)、新PropertyMetadata(可见性.折叠));
公众能见度
{
获取{return(可见性)GetValue(TotalPresenterVisibilityProperty);}
集合{SetValue(TotalPresenterVisibilityProperty,value);}
}
受保护的覆盖无效附加()
{
base.onatached();
AssociatedObject.Sorting+=AssociatedObjectOnSorting;
}
私有void AssociatedObjectOnSorting(对象发送方、DataGridSortingEventArgs DataGridSortingEventArgs)
{
var columnSortMemberPath=dataGridSortingEventArgs.Column.SortMemberPath;
if(columnSortMemberPath!=“价格”)
返回;
TotalPresenterVisibility=TotalPresenterVisibility==可见性。可见
?能见度。倒塌
:能见度。可见;
}
附加时受保护的覆盖无效()
{
base.OnDetaching();
AssociatedObject.Sorting-=AssociatedObjectOnSorting;
}
}
四,。BaseObserveObject代码(对于.net 4.5):

公共类BaseObserveObject:INotifyPropertyChanged
{
公共事件属性更改事件处理程序属性更改;
受保护的虚拟void OnPropertyChanged([CallerMemberName]字符串propertyName=null)
{
var handler=PropertyChanged;
if(handler!=null)handler(这是新的PropertyChangedEventArgs(propertyName));
}
受保护的虚拟void OnPropertyChanged(表达式提升器)
{
var propName=((MemberExpression)raiser.Body).Member.Name;
OnPropertyChanged(propName);
}
受保护的布尔集合(参考T字段,T值,[CallerMemberName]字符串名称=null)
{
如果(!EqualityComparer.Default.Equals(字段,值))
{
字段=值;
OnPropertyChanged(名称);
返回true;
}
返回false;
}
}
如果您在代码方面遇到问题,我很乐意提供帮助。问候

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