我创建了一个公开 DependencyProperty 的 UserControl:
namespace MyApp.Sql
{
public partial class SqlConnectionStringBuilder
{
private static readonly SqlConnectionString DefaultValue = new SqlConnectionString { IntegratedSecurity = true, Pooling = false };
public static readonly DependencyProperty ConnectionStringProperty =
DependencyProperty.Register("ConnectionString", typeof(SqlConnectionString),
typeof (SqlConnectionStringBuilder),
new FrameworkPropertyMetadata(
DefaultValue,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
ConnectionStringChanged));
private static void ConnectionStringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var builder = (SqlConnectionStringBuilder) d;
if (e.NewValue == null)
builder.Dispatcher.BeginInvoke((Action)(() => d.SetValue(ConnectionStringProperty, DefaultValue)));
else
builder.RegisterNewConnectionString((SqlConnectionString)e.NewValue);
}
public SqlConnectionString ConnectionString
{
get { return (SqlConnectionString)GetValue(ConnectionStringProperty); }
set { SetValue(ConnectionStringProperty, value); }
}
private void RegisterNewConnectionString(SqlConnectionString newValue)
{
if (newValue != null)
newValue.PropertyChanged += ConnectionStringPropertyChanged;
}
...
}
}
现在我尝试在另一个 UserControl 中使用 ConnectionString 并将 TextBlock 附加到 ConnectionString:
</UserControl.Resources>
<Grid Grid.IsSharedSizeScope="True">
<Grid.RowDefinitions>
<RowDefinition Height="1*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<MyApp.Sql:SqlConnectionStringBuilder ConnectionString="{Binding ElementName=_this, Path=ServerConnectionString}" />
<TextBlock Text="{Binding ElementName=_this, Path=ServerConnectionString, StringFormat='Produced Connection String: {0}'}"
Grid.Row="1" />
</Grid>
namespace MyApp
{
public partial class SqlProvider
{
public SqlProvider
{
InitializeComponent();
DataContext = this;
}
private SqlConnection _connection;
public SqlConnection ServerConnectionString
{
get { return _connection; }
set
{
_connection = value;
OnPropertyChanged("ServerConnectionString");
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
但是 SqlConnectionString 永远不会分配给 TextBlock。当我调试 ConnectionStringBuilder 的 SqlConnection 属性时,它总是显示 null
我的错在哪里?