【发布时间】:2020-08-08 01:59:56
【问题描述】:
我在演示 WPF 项目中遇到了困难。我必须认识到我有许多使代码复杂化的约束。
核心元素是一个继承自 UserControl 的控件。我想尽可能保持其代码隐藏。另外,我希望将其 XAML 放在 ControlTemplate 中。它的 C# 代码应该在一个专用的 ViewModel 中(这个例子是一个巨大的项目,拥有一个专用的 viewModel 可以帮助将所有的 viewmodel 分组。但无论如何,说它是强制性的)。 最后但同样重要的是,我想将此控件的 2 个属性绑定到外部属性。
这是我的 MainWindow.xaml 文件:
<Window x:Class="ViewModel_defined_in_ControlTemplate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ViewModel_defined_in_ControlTemplate"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="MyDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<StackPanel>
<local:MyUserControl Template="{StaticResource TextBoxTemplate}"
NomPersonne="sg"/>
<Button Content="Click me!" Command="{Binding ElementName=MyViewModel,Path=ChangeTextBoxContent}" Width="100" HorizontalAlignment="Left"/>
</StackPanel>
</Grid>
</Window>
该按钮只是更改 NomPersonne 依赖属性的值(见下文)。 MyDictionary.xaml 包含 ControlTemplate:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ViewModel_defined_in_ControlTemplate">
<ControlTemplate x:Key="TextBoxTemplate" TargetType="{x:Type local:MyUserControl}">
<Grid>
<Grid.DataContext>
<local:MyViewModel/>
</Grid.DataContext>
<TextBox Width="50" HorizontalAlignment="Left" Text="{TemplateBinding NomPersonne}"/>
</Grid>
</ControlTemplate>
</ResourceDictionary>
我不知道将我的依赖属性放在哪里,以及如何访问它。 我试着把它放在 MyUserControl 中:
namespace ViewModel_defined_in_ControlTemplate
{
public partial class MyUserControl : UserControl
{
public string NomPersonne
{
get { return (string)GetValue(NomPersonneProperty); }
set { SetValue(NomPersonneProperty, value); }
}
public static readonly DependencyProperty NomPersonneProperty =
DependencyProperty.Register("NomPersonne", typeof(string), typeof(MyUserControl), new PropertyMetadata(""));
}
}
现在可以从 MyUserCONtrol 的 XAML 访问它,但是我不知道如何访问它以便让按钮的命令更改属性:
namespace ViewModel_defined_in_ControlTemplate
{
public class MyViewModel : ViewModelBase
{
public RelayCommand ChangeTextBoxContent = new RelayCommand(() =>
{
//...
}, () => true);
}
}
我宁愿在视图模型中拥有依赖属性,但在这种情况下,我如何在 MainWindow 中的 MyUserControl 的 XAML 中访问?
谢谢。
【问题讨论】:
标签: c# wpf mvvm dependency-properties