MTR*_*MTR 12 .net data-binding wpf xaml
我正在尝试将TextBlock绑定到ObservableCollection中的特定元素.这就是我现在所做的:
private ObservableCollection<double> arr = new ObservableCollection<double>();
public ObservableCollection<double> Arr { get { return arr; } set { arr = value; } }
testBox.DataContext = this;
private void Button_Click(object sender, RoutedEventArgs e)
{
Arr[0] += 1.0;
}
[ValueConversion(typeof(ObservableCollection<double>), typeof(String))]
public class myObsCollConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
ObservableCollection<double> l = value as ObservableCollection<double>;
if( l == null )
return DependencyProperty.UnsetValue;
int i = int.Parse(parameter.ToString());
return l[i].ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
<Window.Resources>
<local:myObsCollConverter x:Key="myConverter"/>
</Window.Resources>
<TextBlock Name="testBox" Text="{Binding Path=Arr,Converter={StaticResource myConverter}, ConverterParameter=0}" />
Run Code Online (Sandbox Code Playgroud)
我看到的是testBox在创建时显示了Arr的第一个值.但它并没有反映出这个元素的任何变化.为了在textBox中看到Arr [0]的更改,我该怎么办?
Chr*_*Wue 22
无需转换器.你可以直接绑定到Arr[0]这样
<TextBlock Name="testBox" Text="{Binding Path=Arr[0]}"/>
Run Code Online (Sandbox Code Playgroud)
虽然为了动态更新,但是Arr需要实现这些元素INotifyPropertyChanged.
更新:详细说明:
public class MyDouble : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private double _Value;
public double Value
{
get { return _Value; }
set { _Value = value; OnPropertyChanged("Value"); }
}
void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后
ObservableCollection<MyDouble> Arr { get; set; }
Run Code Online (Sandbox Code Playgroud)
并绑定到
<TextBlock Name="testBox" Text="{Binding Path=Arr[0].Value}"/>
Run Code Online (Sandbox Code Playgroud)
ObservableCollections不会将更改传播到存储在属于集合的对象中的值.它只会在集合本身的内容发生变化时触发通知(即添加,删除,重新排序项目).如果您想要在集合中的值发生更改时更新UI,那么您必须单独连接自己.
| 归档时间: |
|
| 查看次数: |
24250 次 |
| 最近记录: |