목록 상자에서 텍스트 상자 항목을 선택해도 목록 상자의 선택한 항목은 변경되지 않습니다.
텍스트 상자 목록을 표시하는 wpf 목록 상자가 있습니다.텍스트 상자를 클릭해도 목록 상자 선택은 변경되지 않습니다.목록 상자 항목을 선택하려면 텍스트 상자 옆을 클릭해야 합니다.클릭 이벤트를 목록 상자로 전달하기 위해 텍스트 상자에 설정해야 하는 속성이 있습니까?
다음 스타일을 사용하여 TextBox 컨트롤 및 ComboBox 등의 모든 이벤트를 처리하는 PreviewGotKeyboardFocus를 설정합니다.
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
</Style>
</ListView.ItemContainerStyle>
그런 다음 코드 뒤에 있는 행을 선택합니다.
protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
{
ListViewItem item = (ListViewItem) sender;
item.IsSelected = true;
}
반드시 적절한 Target Type: List View를 사용하십시오.항목, ListBoxItem 또는 TreeViewItem.
<Style TargetType="ListViewItem">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="true">
<Setter Property="IsSelected" Value="true" />
</Trigger>
</Style.Triggers>
</Style>
댓글이 부족해서 댓글로 올립니다.의 그레이저은 그레이저와 하지 않습니다.Button한 SelectedItem은, 「 」에 「 」가 되어 있기 입니다.Style Trigger , . . . . . . . .IsKeyboardFocusWithin when becomes becomes becomes 가 、 [ False ]Button및 , 。SelectedItem무효가 됩니다.
Robert의 솔루션과 비슷하지만 코드 배후에 (첨부된 동작을 사용하여) 코드를 사용하지 않습니다.
그렇게 하기 위해서,
먼저 별도의 클래스 Focus Behaviour를 만듭니다.
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace MyBehaviours
{
public class FocusBehaviour
{
#region IsFocused
public static bool GetIsFocused(Control control)
{
return (bool) control.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(Control control, bool value)
{
control.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached(
"IsFocused",
typeof(bool),
typeof(FocusBehaviour),
new UIPropertyMetadata(false, IsFocusedPropertyChanged));
public static void IsFocusedPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var control = sender as Control;
if (control == null || !(e.NewValue is bool))
return;
if ((bool)e.NewValue && !(bool)e.OldValue)
control.Focus();
}
#endregion IsFocused
#region IsListBoxItemSelected
public static bool GetIsListBoxItemSelected(Control control)
{
return (bool) control.GetValue(IsListBoxItemSelectedProperty);
}
public static void SetIsListBoxItemSelected(Control control, bool value)
{
control.SetValue(IsListBoxItemSelectedProperty, value);
}
public static readonly DependencyProperty IsListBoxItemSelectedProperty = DependencyProperty.RegisterAttached(
"IsListBoxItemSelected",
typeof(bool),
typeof(FocusBehaviour),
new UIPropertyMetadata(false, IsListBoxItemSelectedPropertyChanged));
public static void IsListBoxItemSelectedPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var control = sender as Control;
DependencyObject p = control;
while (p != null && !(p is ListBoxItem))
{
p = VisualTreeHelper.GetParent(p);
}
if (p == null)
return;
((ListBoxItem)p).IsSelected = (bool)e.NewValue;
}
#endregion IsListBoxItemSelected
}
}
둘째, 리소스 섹션에 스타일을 추가합니다(내 스타일은 포커스에 검은색으로 표시됩니다).Focus Behavior (초점 동작)IsListBoxItemSelected 。.xmlns:behave="clr-namespace:MyBehaviours"
`
<Style x:Key="PreviewTextBox" BasedOn="{x:Null}" TargetType="{x:Type TextBox}">
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="AllowDrop" Value="true"/>
<Setter Property="Background" Value="White"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border
Margin="6,2,0,4"
BorderBrush="#FFBDBEBD"
BorderThickness="1"
CornerRadius="8"
Background="White"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
MinWidth="100"
x:Name="bg">
<ScrollViewer
x:Name="PART_ContentHost"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="Background" TargetName="bg" Value="Black"/>
<Setter Property="Background" Value="Black"/><!-- we need it for caret, it is black on black elsewise -->
<Setter Property="Foreground" Value="White"/>
<Setter Property="behave:FocusBehaviour.IsListBoxItemSelected" Value="True"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
`
세 번째 (옵션, 리버스 태스크의 경우)
List Box Item listbox에 Text Box 、 List Box 。행동 클래스의 또 다른 속성인 IsFocused를 사용할 것을 권장합니다. 샘플 .ListBoxItemProperty="behave:FocusBehaviour.IsFocused" ★★★★★★★★★★★★★★★★★」FocusManager.IsFocusScope="True"
<DataTemplate x:Key="YourKey" DataType="{x:Type YourType}">
<Border
Background="#FFF7F3F7"
BorderBrush="#FFBDBEBD"
BorderThickness="0,0,0,1"
FocusManager.IsFocusScope="True"
x:Name="bd"
MinHeight="40">
<TextBox
x:Name="textBox"
Style="{StaticResource PreviewTextBox}"
Text="{Binding Value}" />
</Border>
<DataTemplate.Triggers>
<DataTrigger
Binding="{Binding IsSelected,RelativeSource={RelativeSource AncestorType=ListBoxItem}}"
Value="True">
<Setter
TargetName="textBox"
Property="behave:FocusBehaviour.IsFocused"
Value="True" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
클릭 이벤트를 목록 상자로 전달하기 위해 텍스트 상자에 설정해야 하는 속성이 있습니까?
간단한 자산은 아니지만 이 이벤트를 처리할 수 있습니다.TextBoxVisual Tree Helper를 사용하여 다음 명령을 검색합니다.ListBoxItem그것을 선택합니다.
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox myTextBox = sender as TextBox;
DependencyObject parent = VisualTreeHelper.GetParent(myTextBox);
while (!(parent is ListBoxItem))
{
parent = VisualTreeHelper.GetParent(parent);
}
ListBoxItem myListBoxItem = parent as ListBoxItem;
myListBoxItem.IsSelected = true;
}
클래스 핸들러를 사용하여 이 동작을 설정합니다.이렇게 하면 응용프로그램의 모든 목록 보기가 수정됩니다.이것이 기본 동작이 아닌 이유를 알 수 없습니다.
App.xaml.cs에서 OnStartup에 다음 항목을 추가합니다.
protected override void OnStartup(StartupEventArgs e)
{
EventManager.RegisterClassHandler(typeof (ListViewItem),
ListViewItem.PreviewGotKeyboardFocusEvent,
new RoutedEventHandler((x,_) => (x as ListViewItem).IsSelected = true));
}
이 작업을 수행하는 가장 간단한 방법은 미리보기를 사용하는 것입니다.MouseDown 이벤트 및 템플리트된 부모의 IsSelected 속성을 설정합니다.미리보기 이벤트가 버블다운되므로 ListBoxItem은 사용자가 텍스트 상자, 콤보 상자 또는 사용자가 이벤트를 설정한 다른 컨트롤을 클릭하는 즉시 이벤트를 처리합니다.
이 기능의 장점 중 하나는 모든 유형의 컨트롤이 Framework 요소에서 파생되므로 동일한 이벤트를 사용할 수 있다는 것입니다.또한 (Selected Item을 설정하는 대신) IsSelected를 설정하면 목록 상자의 선택 모드를 "확장"으로 설정할 때 여러 항목이 선택됩니다.이 경우 원하는 항목이 선택되거나 선택되지 않을 수 있습니다.
즉,
c# 코드
private void Element_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
((sender as FrameworkElement).TemplatedParent as ListBoxItem).IsSelected = true;
}
xaml
...
<ComboBox PreviewMouseDown="Element_PreviewMouseDown"/>
<TextBox PreviewMouseDown="Element_PreviewMouseDown"/>
...
이것이 당신이 찾고 있는 답입니다: 내부 ComboBox에 초점이 맞춰져 있을 때 ListBoxItem을 선택합니다.
옛날 얘기지만, 내 대답이 다른 사람들에게 도움이 될지도 몰라.
Ben의 솔루션은 Grazer의 솔루션과 같은 문제를 안고 있습니다.단점은 텍스트 상자의 [키보드] 포커스에 따라 선택이 다르다는 것입니다.대화 상자에 다른 컨트롤이 있는 경우(즉, 버튼) 버튼을 클릭하면 포커스가 사라지고 목록 상자 항목이 선택 해제됩니다(선택됨).항목 == null).따라서 항목을 클릭하는 동작(텍스트 상자 외부)과 텍스트 상자를 클릭하는 동작은 다릅니다.이것은 다루기가 매우 지루하고 매우 이상하게 보인다.
순수 XAML 솔루션은 존재하지 않을 것입니다.이걸 하려면 코드 배후에 있어야 해그 해결책은 마크가 제안한 것에 가깝다.
(이 예에서는 ListView를 사용하고 있습니다.ListBoxItem이 아닌 Item이지만 솔루션은 둘 다에 대해 작동합니다.)
코드 비하인드:
private void Element_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
var frameworkElement = sender as FrameworkElement;
if (frameworkElement != null)
{
var item = FindParent<ListViewItem>(frameworkElement);
if (item != null)
item.IsSelected = true;
}
}
Find Parent (http://www.infragistics.com/community/blogs/blagunas/archive/2013/05/29/find-the-parent-control-of-a-specific-type-in-wpf-and-silverlight.aspx 에서 취득):
public static T FindParent<T>(DependencyObject child) where T : DependencyObject
{
//get parent item
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
//we've reached the end of the tree
if (parentObject == null) return null;
//check if the parent matches the type we're looking for
T parent = parentObject as T;
if (parent != null)
return parent;
return FindParent<T>(parentObject);
}
Data Template:
<TextBox Text="{Binding Name}"
PreviewMouseDown="Element_PreviewMouseDown"/>
DataTemplate @Ben benbenbenben 。이치노ListView를 GridView > GridViewColumn > TextBox.
예:
<ListView.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="IsSelected" Value="True"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</ListView.Resources>
Arcturus Answer를 기반으로 한 첨부 동작으로 재사용이 가능하며, 뒤에 있는 코드에 숨겨져 있지 않습니다.
동작 첨부 파일 생성(= 속성 첨부)
public static class SelectListBoxItemWhenControlInsideTheItemIsClickedBehavior
{
public static readonly DependencyProperty EnableProperty = DependencyProperty.RegisterAttached(
"Enable",
typeof(bool),
typeof(SelectListBoxItemWhenControlInsideTheItemIsClickedBehavior),
new FrameworkPropertyMetadata(false, OnEnableChanged));
public static bool GetEnable(FrameworkElement frameworkElement)
{
return (bool)frameworkElement.GetValue(EnableProperty);
}
public static void SetEnable(FrameworkElement frameworkElement, bool value)
{
frameworkElement.SetValue(EnableProperty, value);
}
private static void OnEnableChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if ( d is ListBoxItem listBoxItem)
listBoxItem.PreviewGotKeyboardFocus += ListBoxItem_PreviewGotKeyboardFocus;
}
private static void ListBoxItem_PreviewGotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
{
var listBoxItem = (ListBoxItem)sender;
listBoxItem.IsSelected = true;
}
}
원하는 리소스에 추가합니다.
를 들어, 「」입니다.<Windows.Resources>
<Window.Resources>
<Style TargetType="ListViewItem">
<Setter Property="myBehavior:SelectListBoxItemWhenControlInsideTheItemIsClickedBehavior.Enable" Value="true"/>
</Style>
</Window.Resources>
네임스페이스 추가
비주얼 스튜디오가 자동으로 추가할 수 없을 정도로 똑똑하지 않은 경우.예를 들어 프로젝트 이름이 "MyApp"이고 파일을 "MyBehaviors" 폴더에 저장한 경우 네임스페이스는 Window:
<Window
xmlns:myBehavior="clr-namespace:MyApp.MyBehaviors"
>
목록 상자는 항목 선택을 처리하지만 내장된 텍스트 상자의 포커스에 대해서는 알 수 없습니다.텍스트 상자가 입력 포커스를 받을 때마다 선택을 변경하려면 목록 상자 선택을 수동으로 변경해야 합니다.
이전 답변에서 설명한 대로 선택을 직접 설정하고 싶은지는 잘 모르겠습니다.멀티세션이나 다른 시나리오가 깨질 것 같기 때문입니다.
. 아래와 같은 버튼의 재타일을 시도하여 결과를 보는 것이 좋습니다.
<Button ClickMode="Pressed" Focusable="False">
<Button.Template>
<ControlTemplate> // change the template to get rid of all the default chrome
<Border Background="Transparent"> // Button won't be clickable without some kind of background set
<ContentPresenter />
</Border>
</ControlTemplate>
</Button.Template>
<TextBox />
당신은 초기 상황에 대해 그다지 구체적이지 않습니다.그러나 DataBinding과 ItemTemplate를 사용하고 있다고 생각합니다.이 주제에 대한 당신의 초보자들도 이 방법을 쉽게 사용할 수 있습니다.이 조작은 유효합니다.
<ListBox ItemsSource="{Binding someDataCollection}" Name="myListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding datafield}" Tag="{Binding .}"
GotFocus="TextBox_GotFocus"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
myListBox.SelectedItem = (sender as TextBox).Tag; /* Maybe you need to cast to the type of the objects contained in the collection(bound as ItemSource above) */
}
다음 코드를 사용해 보십시오.
foreach (object item in this.listBox1.Items) {
if (textbox1.text.equals(item.toString())) {
//show error message; break
}
}
언급URL : https://stackoverflow.com/questions/653524/selecting-a-textbox-item-in-a-listbox-does-not-change-the-selected-item-of-the-l
'programing' 카테고리의 다른 글
| 바닐라 Javascript를 사용하여 HTML 테이블을 CSV로 내보내기 (0) | 2023.09.02 |
|---|---|
| MySQL의 저장 프로시저 내에 선택적 매개 변수를 작성하시겠습니까? (0) | 2023.09.02 |
| 왜 차르가 없지?문자열처럼 비어 있습니다.비어있나요? (0) | 2023.04.20 |
| VBA를 사용하여 Range를 사용하여 전체 Excel 시트를 선택하려면 어떻게 해야 합니까? (0) | 2023.04.20 |
| SQL Server PRINT SELECT (선택한 쿼리 결과를 인쇄하시겠습니까?) (0) | 2023.04.20 |