/ /ユーザーコントロールへのバインドが機能しない-wpf、データバインディング、ユーザーコントロール

バインドされていないusercontrolが動作しない - wpf、data-binding、user-controls

データバインディングの問題が発生しました だから私はusercontroleを作成します

UserControl1.xaml.cs

public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public static DependencyProperty TestThisProperty = DependencyProperty.Register
(
"TestThis",
typeof(string),
typeof(UserControl1),
new PropertyMetadata("Some Data",new PropertyChangedCallback(textChangedCallBack))
);
public string TestThis
{
get { return (string)GetValue(TestThisProperty); }
set { SetValue(TestThisProperty, value); }
}
static void textChangedCallBack(DependencyObject property, DependencyPropertyChangedEventArgs args)
{
UserControl1 _us = (UserControl1)property;

_us.MyUserControl.TestThis = (string)args.NewValue;

}
}

UserControl1.xaml

<UserControl x:Class="WpfApplication1.UserControl1"
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"
mc:Ignorable="d"  x:Name="MyUserControl"

d:DesignHeight="300" d:DesignWidth="300">
</UserControl>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
UserControl1 _uc = new UserControl1();

public MainWindow()
{
InitializeComponent();
DispatcherTimer _dt = new DispatcherTimer();
_dt.Interval = new TimeSpan(0, 0, 1);
_dt.Start();
_dt.Tick += new EventHandler(_dt_Tick);
}
private void _dt_Tick(object s,EventArgs e)
{
_uc.TestThis = DateTime.Now.ToString("hh:mm:ss");

}

最後にMainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">

<Grid>
<TextBox Text="{Binding Path=TestThis,ElementName=MyUserControl, UpdateSourceTrigger=PropertyChanged}"/>

</Grid>

しかし、ここでの問題は、コードをデバッグするときにこの警告が表示されることです 参照「ElementName = MyUserControl」のバインディングのソースが見つかりません。そして、UIはもちろん更新されません、何か考えてください?

回答:

回答№1の場合は3

ElementName 同じ名前のターゲットのみ namescope

<TextBox Name="tb"/>
<Button Content="{Binding Text, ElementName=tb}"/>

でUserControlを定義しない場合 MainWindow XAMLを使用して、そこに名前を付けるか、 名前を登録する コードビハインド(そしてそれをターゲットにする)では、これは得られません ElementName 仕事への結合。

別の方法は、ユーザーコントロールをメインウィンドウのプロパティとして公開することです。

public UserControl1 UC { get { return _uc; } }

次に、次のようにバインドできます。

{Binding UC.TestThis, RelativeSource={RelativeSource AncestorType=Window}}