感谢任何帮助。我是WPF的新手。我有一个由xml文件填充的树视图。选择树视图项后,我需要它显示在文本框中。我在弹出窗口中有树视图,我已经得到它,以便在选择有问题的文本框时,它将弹出带有树视图的弹出窗口,提示用户在树视图上进行选择。之后,它应该将树视图选择放回到同一文本框中。这是我的代码:
<TextBox Name="text"
Text="{Binding Path=SelectedItem.name, ElementName=dirTree}"
Style="{StaticResource CustomTextBoxStyle}"
Grid.Column="1"
Margin="47,326,110,140"
TextChanged="text_TextChanged" />
树视图部分:
<Popup PlacementTarget="{Binding ElementName=text}"
VerticalOffset="20"
HorizontalOffset="-180"
Margin="0,0,465,279"
Name="popup1"
AllowsTransparency="True"
Placement="Top">
<Popup.Style>
<Style TargetType="{x:Type Popup}">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=text, Path=IsFocused}"
Value="True">
<Setter Property="IsOpen"
Value="True" />
</DataTrigger>
<!--<DataTrigger Binding="{Binding ElementName=popupText, Path=IsFocused}"
Value="True">
<Setter Property="IsOpen"
Value="True" />
</DataTrigger>-->
</Style.Triggers>
</Style>
</Popup.Style>
<Grid>
<Border BorderThickness="2"
Background="DodgerBlue"
BorderBrush="DodgerBlue"
Padding="0"
CornerRadius="6">
<ScrollViewer Height="300"
Name="scrollViewer1"
Width="175"
BorderBrush="Black"
Background="DodgerBlue">
<TreeView Name="dirTree"
ItemsSource="{Binding Source={StaticResource xmldata}, XPath=.}"
VirtualizingStackPanel.IsVirtualizing="False"
VirtualizingStackPanel.VirtualizationMode="Standard"
GotFocus="TreeView1_GotFocus"
SelectedItemChanged="{Binding ElementName=dirTree, Path=SelectedItem}"/>
</ScrollViewer>
</Border>
</Grid>
</Popup>
答案 0 :(得分:1)
从TreeView在SelectedItemChanged事件上创建一个事件处理程序,然后从那里更新TextBlock.Text。
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TreeView x:Name="demoTreeView"
Margin="10"
SelectedItemChanged="demoTreeView_SelectedItemChanged">
</TreeView>
<TextBlock x:Name="demoTextBox" Grid.Row="1"/>
</Grid>
在.cs文件中:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
demoTreeView.Items.Add("test1");
demoTreeView.Items.Add("test2");
demoTreeView.Items.Add("test3");
demoTreeView.Items.Add("test4");
}
private void demoTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
demoTextBox.Text = e.NewValue.ToString();
}
}
个性我建议你在属性上使用MVVM和绑定,以便在xaml和代码隐藏之间实现良好的解耦。