爲您的用戶控件添加一個依賴項屬性並綁定到xaml中,如下所示。
public static readonly DependencyProperty ProductProperty = DependencyProperty.Register(
"Product", typeof(ProductDto), typeof(ProductUserControl), new FrameworkPropertyMetadata(null));
public ProductDto Product
{
get { return (ProductDto)this.GetValue(ProductProperty); }
set { this.SetValue(ProductProperty, value); }
}
<TextBox Margin="2" Text="{Binding Path=Product.Code, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Margin="2" Text="{Binding Path=Product.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
你應該有你的Window_NewProduct的視圖模型的產品屬性
public class Window_NewProductViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private ProductDto product;
public ProductDto Product
{
get
{
return this.product;
}
set
{
if (value != this.product)
{
this.product = value;
NotifyPropertyChanged();
}
}
}
}
然後在Window_NewProduct XAML則不應將此屬性綁定到用戶控件依賴屬性
<local:ProductUserControl x:Name="ProductUserControl" Product="{Binding Product}"/>
添加參數Window_NewProduct構造函數接受ProductDto並將其傳遞給ViewModel。
public Window_NewProduct(ProductDto product)
{
InitializeComponent();
this.DataContext = new Window_NewProductViewModel() { Product = product };
}
然後在你的MainWindow中,你可以創建一個新的productDto傳遞給DetailsWindow。
var newProduct = new ProductDto();
var window_NewProduct = new Window_NewProduct(newProduct);
if (window_NewProduct.ShowDialog() == true)
{
Debug.WriteLine(newProduct.Code);
Debug.WriteLine(newProduct.Name);
}
我得到一個XamlParseException當我運行它 – user5552042
我收到產品屬性的添加依賴屬性之後,但在產品綁定的是引起異常 – user5552042