我一直在阅读有关用户和自定义控件之间差异的一些解释,例如:http: //www.wpftutorial.net/CustomVsUserControl.html
例如,我想创建一个带有2个组合框的数据网格的简单组合,这些组合框负责更改数据网格项目的值.我想为此创建一个特定的控件,因为我将使用它很多次.我想实现后面的逻辑然后在xaml调用中我只需要指定itemsSource.
对于此示例,我应该创建用户控件还是自定义控件?由于我将拥有属性和逻辑,我应该有一个用于此控件的viewmodel吗?
编辑:你知道一些文章在这两个选项之间有明确的概念分离吗?
我最好通过例子问这个问题.假设我有UserControl和Window使用此控件.
我想以这种方式设计这个控件(名为MyControl)(这是科幻语法!):
<Grid>
<Button>Just a button</Button>
<PlaceHolder Name="place_holder/>
</Grid>
Run Code Online (Sandbox Code Playgroud)
在设计我的Window时以这种方式使用:
<MyControl/>
Run Code Online (Sandbox Code Playgroud)
要么
<MyControl>
<place_holder>
<Button>Button 1</Button>
</place_holder>
</MyControl>
Run Code Online (Sandbox Code Playgroud)
要么
<MyControl>
<place_holder>
<Button>Button 1</Button>
<Button>Button 2</Button>
</place_holder>
</MyControl>
Run Code Online (Sandbox Code Playgroud)
当然我希望能够在Window中为MyControl添加更多元素.因此,在某种程度上它应该作为容器(如Grid,StackPanel等)工作.该位置将在UserControl中定义(在此示例中,在按钮"只是一个按钮"之后)但是要添加的内容(哪些元素)将在Window中定义(使用UserControl - MyControl).
我希望这很清楚我想要实现的目标.关键点是在设计Window时使用XAML,因此我的类应该不比其他控件差.
现在,最大的问题是 - 如何做到这一点?
备注:样式超出范围.我想要做的就是在设计Window时添加我想要的任何控件MyControl(而不是在设计MyControl时).
我在WPF中有一个控件,它有一个独特的Uid.我怎样才能通过其Uid来回溯对象?
我正在使用DevExpress的WPF树列表视图,我发现了我认为与用作项目源的对象重命名属性相关的更普遍的问题.在树列表视图中,需要指定ParentFieldName和KeyFieldName(用于确定树的结构).这些字段是字符串.
这导致了重构代码的问题.例如,重命名我用作ItemSource的对象的属性将破坏树视图,因为ParentFieldName和KeyFieldName不再与属性名称同步.我通过在我的视图模型"ParentFieldName"和"KeyFieldName"中创建属性来解决这个问题,它使用nameof向视图显示属性名称.
这是控件的简化版本:
<UserControl
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"
xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.DataContext>
<ViewModel />
</UserControl.DataContext>
<dxg:TreeListControl AutoGenerateColumns="AddNew"
EnableSmartColumnsGeneration="True" ItemsSource="{Binding Results}"
SelectionMode="Row">
<dxg:TreeListControl.View>
<dxg:TreeListView
ParentFieldName="{Binding ParentIdFieldName}" KeyFieldName="{Binding NodeIdFieldName}"
ShowHorizontalLines="False" ShowVerticalLines="False"
ShowNodeImages="True"/>
</dxg:TreeListControl.View>
</dxg:TreeListControl>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
和viewmodel:
using DevExpress.Mvvm;
public sealed class ViewModel : ViewModelBase
{
public string ParentIdFieldName => nameof(TreeNode.ParentId);
public string NodeIdFieldName => nameof(TreeNode.NodeId);
public ObservableCollection<TreeNode> Results
{
get => GetProperty(() => Results);
set => SetProperty(() => Results, value);
}
}
Run Code Online (Sandbox Code Playgroud)
和树节点:
public sealed class TreeNode
{
public int …Run Code Online (Sandbox Code Playgroud) wpf ×4
wpf-controls ×2
c# ×1
containers ×1
fetch ×1
object ×1
placeholder ×1
viewmodel ×1
xaml ×1