【问题标题】:Bind TextBoxes to List<>[i]将文本框绑定到 List<>[i]
【发布时间】:2020-10-06 03:39:46
【问题描述】:

我的对象如下所示:

public class Macro : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
        private string name = "";
        public string Name
        {
            get { return this.name; }
            set
            {
                this.name = value;
                this.NotifyPropertyChanged("Name");
            }
        }
        private ObservableCollection<int> listParams = new ObservableCollection<int>();
        public ObservableCollection<int> ListParams
        {
            get { return this.listParams; }
            set
            {
                this.listParams = value;
                this.NotifyPropertyChanged("ListParams");
            }
        }

        public Macro()
        {

        }
        public Macro(string nom)
        {
            this.Name = nom;
        }

    }

在我的 XAML 中,我想创建一个 TextBoxes 绑定到 ListParams[0],ListParams[1]... ListParams[20] 的列表。这有可能进行这样的绑定吗?到目前为止,我只创建了 20 个“参数”(int p0, int p1, int p2...),但我正在考虑一种让我的对象更容易的方法。

【问题讨论】:

标签: c# wpf binding


【解决方案1】:

您可以创建一个绑定到ListParamsItemsControl 并将TextBox 放入ItemTemplate

<ItemsControl ItemsSource="{Binding ListParams}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Path=., Mode=OneWay}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

由于int 是不可变的,您将无法使用TextBox 更改它。如果你想要这个,你应该将源集合的类型从ObservableCollection&lt;int&gt; 更改为ObservableCollection&lt;YourClass&gt;,其中YourClass 是一个具有int 属性的类,然后您可以将其绑定到:

<TextBox Text="{Binding Path=IntPropertyOfYourClass}" />

【讨论】:

  • 好的,谢谢,刚刚在阅读有关 ItemsControl 的教程,但我看到您编辑并发布了一个示例,现在就试试,谢谢。
  • 最后我有一个疑问:我打算让我的对象更容易,但最后创建一个特殊的类只是为了存储一些整数可能没有意义?因为在我的所有代码中,只有MyMacro.Pi 将变为MyMacro.ListParams[i].IntProperty... 似乎我让它变得更复杂了?然后也忘记了这个精度,在我的列表框前面,我需要为每个参数放置一些标签“a,b,c,d ...”
  • 你让它对 MVVM 友好。您应该绑定到 view 模型是有原因的。
  • 唯一的原因是我的每个宏都有一个参数列表(最多20个),我想制作一个界面来编辑这些参数(但是一些只有4个参数的宏可能没有使用参数为灰色)。
  • @Siegfried.V:那么你应该使用ItemsControl 和像YourClass 这样的自定义模型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
  • 1970-01-01
  • 2022-07-06
  • 1970-01-01
  • 2011-07-17
  • 1970-01-01
  • 2010-12-18
相关资源
最近更新 更多