我是WPF中的新成員,並嘗試從用戶控件綁定位於mainwindow中的文本框。WPF在用戶控件的主窗口中綁定文本框
<Window x:Class="Databinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="360" Width="490">
<Grid HorizontalAlignment="Left" Width="480">
<TextBox x:Name="EventTitle" HorizontalAlignment="Left" Height="23" Margin="40,19,0,0" TextWrapping="Wrap" Text="{Binding Path=FirstName}" VerticalAlignment="Top" Width="120"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="195,20,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
<StackPanel x:Name="Stck_Main" HorizontalAlignment="Left" Height="230" Margin="22,75,0,0" VerticalAlignment="Top" Width="439"/>
<Button Content="UC" HorizontalAlignment="Left" Margin="371,20,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
</Grid>
我還創建了一個類來管理規定值更新
class UIcontrol : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _firstName;
protected void Notify(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public string FirstName
{
get { return _firstName; }
set
{
if (value != _firstName)
{
_firstName = value;
Notify("FirstName");
}
}
}
}
我的問題:在這個主窗口中我用了一個簡單的用戶控制。我想要綁定來自此用戶控件的文本框值。 綁定通過mainwindow中的按鈕進行操作,但是用戶控件沒有任何反應。我認爲datacontextis錯了,但你能幫我找到正確的方法。在主窗口後面
代碼
public partial class MainWindow : Window
{
private UIcontrol viewModel;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
viewModel = new UIcontrol();
DataContext = viewModel;
viewModel.FirstName = "Mike";
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
UC1 myUC = new UC1();
Stck_Main.Children.Clear();
Stck_Main.Children.Add(myUC);
}
}
用戶控件的代碼背後,是
public partial class UC1 : UserControl
{
private UIcontrol viewModel;
public UC1()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
viewModel = new UIcontrol();
DataContext = viewModel;
viewModel.FirstName = "Doe";
}
}
而且它的XAML:
UserControl x:Class="Databinding.UC1"
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"
d:DesignHeight="300" d:DesignWidth="300">
<Grid Margin="0,0,10,43">
<Canvas Height="194" Margin="25,30,71,0" VerticalAlignment="Top" Background="White">
<Button Content="Button" Canvas.Left="100" Canvas.Top="81" Width="75" Click="Button_Click" />
</Canvas>
</Grid>
可否請你分享的XAML UC1? –
UC1 xaml herunder – GcH
我的理解是你正在看「Mike」而不是「Doe」?正確? –