我有一个未知的变量列表,希望绑定到 WPF 应用程序中的特定控件。有没有办法将列表中的变量绑定到特定名称?
这是我正在尝试做的代码示例。
C#
public class Variable {
public string Name {get;set;}
}
public class VariableViewModel : INotifyPropertyChanged {
Variable _variable;
public Variable Variable {
get {
return(_variable);
}
set {
_variable = value;
if(PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs("Variable"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class VariableListViewModel {
public ObservableCollection<VariableViewModel> VariableList { get; set; }
public VariableListViewModel() {
VariableList = new ObservableCollection<VariableViewModel>();
var variableViewModel = new VariableViewModel {
Variable = new Variable { Name = "my_variable_name" }
};
VariableList.Add(variableViewModel);
}
}
WPF:
<Window>
<Window.DataContext>
<local:VariableListViewModel />
</Window.DataContext>
<StackPanel>
<Label Content="{Binding Path=Name, ElementName=my_variable_name}" />
</StackPanel>
</Window>
这里的标签显然是错误的。我的问题是我想要实现的目标是否可行?我希望能够显示“my_variable_name”。
-斯图尔特