本文介绍了重用xaml用于WPF项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个模态使用控件。它将在很多地方使用。不同的部分是消息部分。 我不知道如何让它重复使用。 <网格边距=10> < Border Background =GhostWhiteBorderBrush =GainsboroBorderThickness =1> < StackPanel Margin =10> < TextBlock Text ={Binding Message}/> < / StackPanel> < / Border> < / Grid> 需要代码而不是概念陈述。 我尝试过: 尝试使用内容模板或datatemplate。只是不知道如何应用它。解决方案 我不会在这里使用模板。模板旨在覆盖或提供UI元素,但如果所有更改的内容都是消息内容,则只需要一个公开的绑定。 在您的代码中执行此操作: 公共部分类MyReusedView:UserControl { public static DependencyProperty MessageProperty = DependencyProperty.Register(Message,typeof(string),typeof(MyReusedView) )); public string消息 { get {return(string)GetValue(MessageProperty); } set {SetValue(MessageProperty,value); } } public MyReusedView() { InitializeComponent(); DataContext = this; } } 然后您在XAML中所需要的只是: < common :MyReusedView Message = {Binding MyMessageSource.Message} /> 作为命名空间隐含的一种,只需确保将类放在足够高的级别,这样你就可以了可以在其他程序集中适当地引用它。 如果你的模态控件已经有一个视图模型作为DataContext,那么你可以在构造函数中使用它: public MyReusedView() { InitializeComponent(); DataContext = new MyReusedViewModel(); 绑定messageBinding = new Binding(Message); messageBinding.Source = DataContext; messageBinding.Mode = BindingMode.OneWayToSource; SetBinding(MyReusedView.MessageProperty,messageBinding); } 这样你就可以在视图模型中保留任何其他逻辑,只需通过视图公开属性,就可以通过XAML访问它。 I have a modal use control. It will be used in many places. The different part is the message part.I am not sure how to make it re-useful.<Grid Margin="10"> <Border Background="GhostWhite" BorderBrush="Gainsboro" BorderThickness="1"> <StackPanel Margin="10"> <TextBlock Text="{Binding Message}" /> </StackPanel> </Border></Grid>Need code rather than concept statements.What I have tried:Tried to use content template or datatemplate. Just don't know how to apply it. 解决方案 这篇关于重用xaml用于WPF项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-24 17:27