这是拥有View Model 的好地方。 Here's another ViewModel link
我要做的是在 ViewModel 中有以下内容(由视图上的组件绑定)
绑定到组合框项目源的 IObservable 属性,您可以根据数组的大小添加/删除该属性
绑定到组合框的 SelectedElement 的选定索引的 int 属性。设置此属性时,您必须执行从字符串到 int 的转换。
绑定到 textbox.text 的字符串属性(您可能在此处使用标签 by),每次更改所选索引的上述 int 属性时都会更新。
如果这完全令人困惑,我可以构建一些伪代码,但这三个属性应该可以工作并得到你想要的。
编辑 - 添加一些代码:
public class YourViewModel : DependencyObject {
public string[] FictionArray {get; private set;}
public IObservable<string> AvailableIndices;
public static readonly DependencyProperty SelectedIndexProperty=
DependencyProperty.Register("SelectedIndex", typeof(string), typeof(YourViewModel), new PropertyMetadata((s,e) => {
var viewModel = (YourViewModel) s;
var index = Convert.ToInt32(e.NewValue);
if (index >= 0 && index < viewModel.FictionArray.Length)
viewModel.TextBoxText=FictionArray[index];
}));
public bool SelectedIndex {
get { return (bool)GetValue(SelectedIndexProperty); }
set { SetValue(SelectedIndexProperty, value); }
}
public static readonly DependencyProperty TextBoxTextProperty=
DependencyProperty.Register("TextBoxText", typeof(string), typeof(YourViewModel));
public bool TextBoxText {
get { return (bool)GetValue(TextBoxTextProperty); }
set { SetValue(TextBoxTextProperty, value); }
}
public YourViewModel(string[] fictionArray) {
FictionArray = fictionArray;
for (int i = 0; i < FictionArray.Length; i++){
AvailableIndices.Add(i.ToString()));
}
}
}
这并不完美,但它应该让您了解如何创建具有可以绑定的属性的视图模型。所以在你的 xaml 中你会有类似的东西:
<ComboBox ItemSource="{Binding AvailableIndices}" SelectedItem="{Binding SelectedIndex}"/>
<TextBox Text="{Binding TextBoxText}"/>