wpf + prism8
需求:需要在长按TextBlock长按一秒变成编辑态,失去焦点后在变成非编辑态
实现:一开始的想法是想直接TextBox用ReadOnly
实现,但是效果不好看,所以打算用切换模板的方式实现,感觉会比两个控件来回隐藏显示好一点吧,话不多说!上代码!
<ListBox
Grid.Row="1"
Margin="3"
HorizontalContentAlignment="Stretch"
ItemsSource="{Binding DataList}"
SelectionMode="Extended">
<ListBox.ItemTemplateSelector>
<local:UITemplateSelector TextBlockTempLate="{StaticResource TextBlockTemplate}" TextBoxTempLate="{StaticResource TextBoxTemplate}" />
</ListBox.ItemTemplateSelector>
</ListBox>
新建一个模板选择器规则在View层调用就可以了,例如新建一个UITemplateSelector
using System.Windows;
using System.Windows.Controls;
using UIEditor.Models;
namespace UIEditor.Common
{
/// <summary>
/// UI列表模板选择器
/// </summary>
public class UITemplateSelector : DataTemplateSelector
{
public DataTemplate TextBoxTempLate { get; set; }
public DataTemplate TextBlockTempLate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
// UITreeModel是我自己定义的一个实体 也是ListBoxItemsSource的数据类型,isInput就是控制是否可以输入状态的变量
var itemData = (UiTreeModel)item;
if (itemData.IsInput == true)
{
return TextBoxTempLate;
}
else
{
return TextBlockTempLate;
}
}
}
}
模板资源
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Wpf">
<DataTemplate x:Key="TextBlockTempLate">
<TextBlock HorizontalAlignment="Stretch" Text="{Binding Name}">
<TextBlock.InputBindings>
<MouseBinding
Command="{Binding Path=DataContext.TextBlock_MouseLeftDoubleDownCmd, RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}}"
CommandParameter="{Binding Id}"
MouseAction="LeftDoubleClick" />
</TextBlock.InputBindings>
</TextBlock>
</DataTemplate>
<DataTemplate x:Key="TextBoxTempLate">
<TextBox
Name="textUserName"
HorizontalAlignment="Stretch"
Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<TextBox.Style>
<Style TargetType="TextBox">
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="VerticalAlignment" Value="Stretch" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsFocused}" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=textUserName}" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
<i:Interaction.Triggers>
<i:EventTrigger EventName="LostFocus">
<i:InvokeCommandAction Command="{Binding Path=DataContext.TextBox_LostFocusCmd, RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}}" CommandParameter="{Binding Id}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
</DataTemplate>
</ResourceDictionary>
完结