我有自定义组合框和自定义箭头。如何通过代码访问此箭头并更改其大小(或使其不可见)x:Name =“Arrow”;
我尝试使用Product_CombBox.FindName(“箭头”),但它不起作用,所以我该怎么做?
<ControlTemplate x:Key="ComboBoxToggleButton" TargetType="ToggleButton">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver"/>
<VisualState x:Name="Pressed"/>
<VisualState x:Name="Disabled"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border x:Name="Border" SnapsToDevicePixels="True" Background="White" BorderBrush="Black" CornerRadius="15" BorderThickness="1" />
<Border x:Name="Border2" SnapsToDevicePixels="True" Background="White" BorderBrush="Black" CornerRadius="15" BorderThickness="1" />
<Path x:Name="Arrow" Data="M 0 0 L 8 12 L 16 0 Z" Fill="Black" Margin="0,0,10,0" HorizontalAlignment="Right" VerticalAlignment="Center" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="ToggleButton.IsMouseOver" Value="true">
</Trigger>
<Trigger Property="ToggleButton.IsChecked" Value="true">
</Trigger>
<!-- <Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="{StaticResource ForegroundDisabledBrush}" />
</Trigger> -->
<DataTrigger Binding="{Binding IsKeyboardFocusWithin, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay}" Value="True">
</DataTrigger >
</ControlTemplate.Triggers>
</ControlTemplate>
答案 0 :(得分:2)
如果ToggleButton
属于Template
较大ComboBox
的一部分,那么您需要先找到ToggleButton
,然后找到Path
。为此,你需要给ToggleButton
一些名字,让我们说x:Name="ToggleButton"
然后:
var button = myComboBox.Template.FindName("ToggleButton", myComboBox) as ToggleButton;
var path = button.Template.FindName("Arrow", button) as System.Windows.Shapes.Path;
答案 1 :(得分:0)
尝试使用 FindVisualChild<T>
功能,如下所示:
private void ChangePath_Click(object sender, RoutedEventArgs e)
{
Path myPath = FindVisualChild<Path>(MyComboBox, "Arrow");
// For example, change fill color
if (myPath != null)
myPath.Fill = Brushes.Red;
}
private childItem FindVisualChild<childItem>(FrameworkElement obj, string elementName) where childItem : FrameworkElement
{
if (obj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
var child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem && (child as childItem).Name == elementName)
return child as childItem;
else
{
childItem childOfChild = FindVisualChild<childItem>(child as FrameworkElement, elementName);
if (childOfChild != null)
return childOfChild;
}
}
}
return null;
}
但这不是在WPF中使用UI的最佳方式。您必须使用样式的强大功能:触发器,DataTriggers,附加行为,以便使用UI正确方便地工作。
你必须坚持一条规则:View
上的任何一方:改变颜色,大小等应该在View
边进行。及时将增长逻辑和代码正在悄悄地变成意大利面条代码。因此,进一步的工作和改变逻辑将是困难的。