我創建的公開一個DependencyProperty的用戶控件:DependencyProperty的未分配
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;
}
...
}
}
現在我嘗試使用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屬性時,它始終顯示爲空
我的錯在哪裏?
您引用的'UserControl'是SqlConnectionStringBuilder,但是您發佈的類是ConnectionStringBuilder,並且不繼承DependencyObject,使DependencyProperty無效,不會繼承UserControl – jimmyjambles
對不起,這是一個複製粘貼misstake ...它的名字是SqlConnectionStringBuilder,它是UserControl的一部分。 – Steve
僅僅因爲它仍然可能是你的代碼不工作的原因,你的SqlConnectionStringBuilder類是否繼承了UserControl? – jimmyjambles