这不是一件容易的事。
我有一个列表框(elementSelection)和一个文本块(elementViewer)。 elementViewer显示数组的一个元素,由elementSelection框选择。所有这一切都有效,即使我以编程方式修改数组中的一个元素,更改也会反映在elementViewer中。 这是代码:
public class ArrElem : INotifyPropertyChanged
{
public ArrElem(double d)
{
wert = d;
}
private double intwert;
public double wert
{
get { return intwert; }
set
{
intwert = value;
NotifyPropertyChanged("wert");
}
}
// Declare the PropertyChanged event
public event PropertyChangedEventHandler PropertyChanged;
// NotifyPropertyChanged will raise the PropertyChanged event passing the
// source property that is being updated.
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
private ObservableCollection<ArrElem> arrField = new ObservableCollection<ArrElem>();
public ObservableCollection<ArrElem> Arr { get { return arrField; } set { arrField = value; } }
private ObservableCollection<int> indexArrField = new ObservableCollection<int>();
public ObservableCollection<int> indexArr { get { return indexArrField; } set { indexArrField = value; } }
public MainWindow()
{
Arr.Add(new ArrElem(1.1));
Arr.Add(new ArrElem(2.2));
for (int i = 0; i < Arr.Count; i++)
{
indexArr.Add(i);
}
InitializeComponent();
DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// this one doesn't show on elementViewer
//double d = Arr[0].wert + 0.1;
//Arr.RemoveAt(0);
//Arr.Insert(0, new ArrElem(d));
// this one shows on elementViewer
Arr[0].wert += 0.1;
}
public class MySpecialMultiConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
int i = int.Parse(values[0].ToString());
ObservableCollection<ArrElem> arr = values[1] as ObservableCollection<ArrElem>;
if (arr == null || i >= arr.Count || i < 0)
return DependencyProperty.UnsetValue;
return arr[i];
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
object[] ooo = new object[1];
ooo[0] = DependencyProperty.UnsetValue;
return ooo;
}
}
<local:MySpecialMultiConverter x:Key="multiConverter" />
<ListBox Name="elementSelection" ItemsSource="{Binding indexArr}"></ListBox>
<TextBlock Name="elementViewer" Text="{Binding Path=wert}" >
<TextBlock.DataContext>
<MultiBinding Converter="{StaticResource multiConverter}">
<Binding ElementName="elementSelection" Path="SelectedIndex" />
<Binding Path="Arr" />
</MultiBinding>
</TextBlock.DataContext>
</TextBlock>
现在我的问题: 正如你在Button_Click的代码中看到的那样,对单个ArrElem的更改显示在elementViewer中,但是如果我替换了ArrElem,则elementViewer不会更新。
在这两种情况下,我需要更改什么才能获得elementViewer的更新?
答案 0 :(得分:1)
我猜在从绑定集合中删除列表框之后,列表框不再具有所选项目。 (SelectedIndex == -1
)。尝试在更改后进行设置:
var selectedIndex = elementSelection.SelectedIndex;
double d = Arr[0].wert + 0.1;
Arr.RemoveAt(0);
Arr.Insert(0, new ArrElem(d));
elementSelection.SelectedIndex = selectedIndex;
BTW:您可以将TextBlock
直接绑定到SelectedItem
的{{1}}媒体资源。无需编写转换器。