【问题标题】:How to access ProgressBar in ListView in C# WPF without Name如何在没有名称的 C# WPF 中访问 ListView 中的 ProgressBar
【发布时间】:2017-09-18 13:59:12
【问题描述】:

我正在使用 WPF 在 C# 中开发一个项目。我有一个ListView,它由绑定到一个对象填充,_name 是该对象的一个​​字段。我希望能够通过知道我要更新的_name 来更新特定的ProgressBar。因此,如果当前_name 是“任务 A”,我想更新与“任务 A”在同一行中的 ProgressBar。但是,由于我无法命名进度条(尝试将数据绑定到名称时收到错误消息),因此我无法弄清楚如何从代码中访问ProgressBar。我尝试过使用标签,但我无法弄清楚如何使用特定标签访问控件。任何帮助将不胜感激。下面显示的是我项目的一些 XAML。

 <ListView.View>
            <GridView>
                <GridViewColumn Width="30">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox Tag="{Binding _name}" IsChecked="True"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Width="200" DisplayMemberBinding="{Binding _name}">Task Name</GridViewColumn>
                <GridViewColumn Width="150">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <ProgressBar Width="145" Height="15" Maximum="100" Value="{Binding _progress}" Tag="{Binding _name}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>

【问题讨论】:

    标签: c# wpf xaml listview


    【解决方案1】:

    您没有访问ProgessBar 元素。相反,您将其Value 属性绑定到您更新的源对象的属性。

    _progress_name(你应该顺便重命名它们)应该是你的数据类型的公共 properties,即你用作 IEnumerable&lt;T&gt; 的类型 T ItemsSourceListView

    这个类应该实现INotifyPropertyChanged :

    public class DataObject : INotifyPropertyChanged
    {
        private double _progress;
        public double Progress
        {
            get { return _progress; }
            set { _progress = value; NotifyPropertyChanged("Progress"); }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName = "")
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    

    <DataTemplate>
        <ProgressBar Width="145" Height="15" Maximum="100" Value="{Binding Progress}" Tag="{Binding _name}"/>
    </DataTemplate>
    

    然后您只需更改ListViewItemsSource 集合中特定项的Progress 属性,例如:

    var col = listView.ItemsSource as List<DataObject>;
    var item = col.FirstOrDefault(x => x.Name == "some name...");
    if(item != null)
        item.Value = 100.0;
    

    【讨论】:

    • 我按照你说的让我的数据对象类实现了 INotifyPropertyChanged,并添加了你显示的事件和函数,但是进度条没有在视觉上更新。如果我在更新进度时调试打印,它会输出正确的数字,因此该字段正在正确更新。
    • 您是否真的绑定到 XAML 中的 属性,而不是绑定到支持字段?
    • 我忘记更新更新属性的代码以使用 Progress 而不是 _progress。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    相关资源
    最近更新 更多