8,757
社区成员




我有一个usercontrol,定义了一个依赖属性MyText,类型是ObservableCollection<string>,但是我修改里面某一项的内容后,没法触发MyText的SetValue,也就是MyText无法感知到列表里的某项已经改变了。请问怎么才能修改数值后自动触发呢?谢谢
1.uc.xaml:
<UserControl x:Class="Test.uc"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Test"
mc:Ignorable="d" d:DesignHeight="100" d:DesignWidth="100">
<Grid>
<ContentControl x:Name="lbl"/>
</Grid>
</UserControl>
2.uc.xaml.cs
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace Test
{
public partial class uc : UserControl
{
public static readonly DependencyProperty MyTextProperty =
DependencyProperty.Register("MyText", typeof(ObservableCollection<string>), typeof(uc), new PropertyMetadata(new ObservableCollection<string>()));
[Bindable(true)]
public ObservableCollection<string> MyText
{
get { return (ObservableCollection<string>)GetValue(MyTextProperty); }
set {
SetValue(MyTextProperty, value);
ObservableCollection<string> lst = value as ObservableCollection<string>;
string s = "";
foreach (string item in lst) s += item;
lbl.Content = s;
}
}
public uc()
{
InitializeComponent();
this.DataContext = this;
}
}
}
3.MainWindow.xaml
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test"
mc:Ignorable="d" Height="100" Width="200">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<local:uc x:Name="uc" MyText="{Binding list}" Grid.Row="0"/>
<Button x:Name="btn" Grid.Row="1" Click="btn_Click"/>
</Grid>
</Window>
4.MainWindow.xaml.cs
using System.Collections.ObjectModel;
using System.Windows;
namespace Test
{
public partial class MainWindow : Window
{
public ObservableCollection<string> list { get; set; } = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
list.Add("a"); list.Add("b");
uc.MyText = this.list;
}
private void btn_Click(object sender, RoutedEventArgs e)
{
list[1] = "c";
uc.MyText = this.list;//必须要加这句强制赋值,界面的标签才会变成ac,注释掉这行后uc就无法感知到?
}
}
}