WPF ComboBox popup placement : Bottom and aligned to the right edge - wpf

I'm trying to create a ComboBox with a non-standard dropdown alignment. Basically, I want the dropdown to be below the ComboBox, but aligned with the right edge of the ComboBox instead of the left edge.
What a normal ComboBox looks like, using PlacementMode="Bottom":
What I want:
I tried to play with the Popup.PlacementMode property in the template of my ComboBox, but none of the possible values seem to do what I want. Is there a simple way to do it, preferably in pure XAML?

When I opened Expression Blend, I have come up with the solution within a few seconds:
<Popup Placement="Left" VerticalOffset="{TemplateBinding ActualHeight}"
HorizontalOffset="{TemplateBinding ActualWidth}"
Sometimes this application is more useful than writing xaml by hands, but not so often.

I would use the "Custom" placementmode for the PopUp and declare a callback to place the popup control into the correct position, like it's shown here: WPF ComboBox DropDown Placement
See if an example here would work for you:
public class TestComboBox : ComboBox
{
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var popup = (Popup)Template.FindName("PART_Popup", this);
popup.Placement = PlacementMode.Custom;
popup.CustomPopupPlacementCallback += (Size popupSize, Size targetSize, Point offset) =>
new[] { new CustomPopupPlacement() { Point = new Point (targetSize.Width-popupSize.Width, targetSize.Height) } };
}
}
hope this helps, regards

Can someone post the complete xaml code please?
I've tried the following:
<ComboBox Grid.Column="1" Height="24" Width="20" HorizontalAlignment="Right"
VerticalAlignment="Top"
Name="comboBox2"
ItemsSource="{Binding Source={StaticResource FilterTypes}}"
SelectedValue="{Binding Path=SelectedType, Mode=TwoWay}" >
<ComboBox.Template>
<ControlTemplate>
<Popup Placement="Left" VerticalOffset="{TemplateBinding ActualHeight}"
HorizontalOffset="{TemplateBinding ActualWidth}" />
</ControlTemplate>
</ComboBox.Template>
</ComboBox>
... after some working and testing I've found a good solution...
<ComboBox.Style>
<Style TargetType="ComboBox" >
<Setter Property="Popup.FlowDirection" Value="RightToLeft"/>
</Style>
</ComboBox.Style>

it's a little hacky, but does work. you just have to change the combobox style.
<Grid Height="40">
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
<FrameworkElement Name="dummy" Visibility="Collapsed">
<FrameworkElement.RenderTransform>
<TransformGroup x:Name="xformgrp">
<TranslateTransform X="{Binding ElementName=PopupContent, Path=ActualWidth}" />
<ScaleTransform ScaleX="-1" />
<TranslateTransform X="{Binding ElementName=chk, Path=ActualWidth}" />
</TransformGroup>
</FrameworkElement.RenderTransform>
</FrameworkElement>
<CheckBox Name="chk" HorizontalAlignment="Center">checkthisout</CheckBox>
<Popup IsOpen="{Binding IsChecked, ElementName=chk}" PlacementTarget="{Binding ElementName=chk}" Placement="Bottom" HorizontalOffset="{Binding ElementName=dummy, Path=RenderTransform.Value.OffsetX}">
<TextBlock Name="PopupContent" Foreground="Yellow" Background="Blue">yeah long popupcontent</TextBlock>
</Popup>
</Grid>
</Grid>
The popups HorizontalOffset just has to get the value of PopupContent.ActualWidth-PlacementTarget.ActualWidth. To get that value I used this trick from Charles Petzold.

Related

WPF : dynamic view/content

I'm a bit beginner in WPF, so I ask this..
Let's say I have a window, and inside the window I want to have something like container, could be just border or maybe panel (in winform terms). The content of container is binded to the selected option (e.g:button). So, for instance, when user selects OPTION 1, the container shows chart; when user selects OPTION 2, the container shows listview filled with data; when user selects OPTION 3, the container shows another things, and so on.
What is the best/nicest (or easiest maybe) approach to do this? I'm thinking about using user control for the content of the container, but don't know if this is nice solution neither the performance for using user control to show little bit complex things and maybe some calculations. Any other idea guys?
To elaborate on #Sheridan's answer, here is a simple TabControl XAML that does what you need:
<TabControl TabStripPlacement="Left">
<TabItem Header="Option 1">
<Grid Background="DarkGray">
<TextBlock Foreground="AliceBlue" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="20" Text="View 1"/>
</Grid>
</TabItem>
<TabItem Header="Option 2">
<Grid Background="DarkBlue">
<TextBlock Foreground="AliceBlue" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="20" Text="View 2"/>
</Grid>
</TabItem>
<TabItem Header="Option 3">
<Grid Background="DarkSlateBlue">
<TextBlock Foreground="AliceBlue" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="20" Text="View 3"/>
</Grid>
</TabItem>
</TabControl>
Result:
You can customize it a little bit by adding this simple Style To your Window.Resources:
<Window.Resources>
<Style TargetType="TabItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabItem">
<RadioButton Content="{TemplateBinding Header}" Margin="2"
IsChecked="{Binding IsSelected, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
Which then results in:
The "WPF Mentality" makes you think the UI controls in terms of their functionality, not their appearance, this is a TabControl =)
I solved this with a ContentControl
MainWindow:
(Define the views you wish to visualize as resources)
<Window.Resources>
<DataTemplate DataType="{x:Type viewModels:SystemPCViewModel}">
<controls:SystemPCControl/>
</DataTemplate>
<DataTemplate DataType="{x:Type viewModels:ChipPCViewModel}">
<controls:ChipPCControl/>
</DataTemplate>
</ResourceDictionary>
</Window.Resources>
<Grid>
<ContentControl Content="{Binding CurrentView}"/>
</Grid>
ViewModel: (can't get much simpler)
public ViewModelBase CurrentView
{
get { return currentView; }
set { Set(() => CurrentView, ref currentView, value); }
}
And there you go, you can change your views by setting the view model for the controls you defined in your MainWindow
private void OnCommandExecuted()
{
CurrentView = someViewModel;
}
private void OnAnotherCommandExecuted()
{
CurrentView = anotherViewModel;
}
HTH!
What you are describing sounds pretty close to a standard TabControl, but with a ControlTemplate that puts the tabs on the left side instead of above the content panel. Using this method would mean having a UserControl in each TabItem, eg. multiple controls. You can find out more about the TabControl from the TabControl Class page at MSDN.

RelativeSource and Popup

The problem is that RelativeSource does not work in the following case. I use silverlight 5.
//From MainPage.xaml
<Grid x:Name="LayoutRoot" Background="White" Height="100" Width="200">
<Popup IsOpen="True">
<TextBlock Text="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType=Grid}}" />
</Popup>
</Grid>
//From MainPage.xaml.cs
public MainPage()
{
InitializeComponent();
DataContext = "ololo";
}
If I set a breakpoint on the binding, I'll get Error:
System.Exception: BindingExpression_CannotFindAncestor.
If I use ElementName=LayoutRoot instead of RelativeSource, everything will be OK.
Why does the relative source binding not work?
Popup is like ContextMenu , ToolTip controls , They are not added to the VisualTree. For this you will have to do like
<Grid x:Name="LayoutRoot" Height="100" Width="200" Background="Black">
<Popup Grid.Row="0" x:Name="popup" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Mode=Self}}">
<TextBlock Text="{Binding DataContext, ElementName=popup}" Background="Red" Width="30" Height="30" />
</Popup>
</Grid>
public MainWindow()
{
InitializeComponent();
DataContext = "abcd";
popup.PlacementTarget = LayoutRoot;
}
I hope this will help.Not like in case of ContextMenu or Tooltip , here you will also have to specify the PlacementTarget.
You can make small hack: setup DataContext via resources.
<Grid.Resources>
<Style TargetType="TextBlock">
<Setter Property="DataContext" Value="{Binding ElementName=myGrid, Path=DataContext}" />
</Style>
</Grid.Resources>
As others have mentioned, it's because the Popup is not part of the visual tree. Instead, you can use the Popup's PlacementTarget property to get back to the visual tree:
<Grid x:Name="LayoutRoot" Background="White" Height="100" Width="200">
<Popup IsOpen="True">
<TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Popup}},
Path=PlacementTarget.DataContext}" />
</Popup>
</Grid>
Popups are not part of the visual tree.
Relative Source "Gets or sets the binding source by specifying its location relative to the position of the binding target (MSDN)". Since Popups are not part of the visual tree of the control that is showing it, it will not be able to resolve anything outside of the popup.

WPF IDataErrorInfo issues

I've used WPF and IDataErrorInfo in the past apps to display errors to the user via a controltemplate by putting an image in the adorner and adding a tooltip to the image like this;
<Style x:Key="textStyle" TargetType="TextBox">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel LastChildFill="True">
<Border BorderBrush="Orange"
BorderThickness="2"
CornerRadius="4"
SnapsToDevicePixels="True">
<Border.Effect>
<DropShadowEffect BlurRadius="10"
ShadowDepth="0"
Color="Orange" />
</Border.Effect>
<DockPanel>
<Image Width="16"
Height="16"
Margin="-20,0,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
RenderOptions.BitmapScalingMode="HighQuality"
Source="{StaticResource imgError}"
ToolTip="{Binding ElementName=adornedElement,
Path=AdornedElement.(Validation.Errors).CurrentItem.ErrorContent}"
ToolTipService.ShowDuration="30000" />
<AdornedElementPlaceholder Name="adornedElement" />
</DockPanel>
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
With the appropriate implementation of IDataErrorInfo in the ViewModel and setting Textbox in the view accordingly the image and tooltip are shown;
<TextBox Name="txt"
Grid.Column="0"
Height="40"
Background="Aqua"
Style="{StaticResource textStyle}"
Text="{Binding Path=Text,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}" />
<TextBlock Grid.Column="1"
Height="40"
Background="AliceBlue"
Text="{Binding ElementName=txt,
Path=(Validation.Errors).CurrentItem.ErrorContent}" />
The above code displays correctly in my previous apps and shows the error in the image tooltip as confirmed by the Textblock.
However, in my current app which is built using Prism I can't get the Image to display. The TextBlock updates correctly and I can set the error to the TextBox tooltip via a style trigger without any issue. The problem is I can't seem to get the image (or anything else) to display in the Adorner. The Image is not shown and border is not changed.
The difference between previous apps and this is that the view is in a Region in a ContentControl and I've used dependency injection to inject the viewmodel into the view constructor and set the DataContext.
I can't figure out why this doesn't work when it did previously. I think I may need to include an AdornerDecorator somewhere but I'm perplexed as to where having tried it in a few places without success. Any ideas how I can ensure the Adorner is shown?
Used an AdornerDecorator to wrap the element containing the texbox and all works fine.

WPF Popup UI showing black

I am using a WPF Popup control, and it is showing the background as black. I put a StackPanel inside it with Background="Transparent", but that does not help.
<Popup PlacementTarget="{Binding ElementName=parentStackPanel}" Placement="Center"
IsOpen="False" Name="m_popWaitNotifier" PopupAnimation="None"
AllowsTransparency="False">
<StackPanel Orientation="Vertical" Background="Transparent">
<uc:CircularProgressBar x:Name="CB" StartupDelay="0"
RotationsPerMinute="20"
Height="25" Foreground="White"
Margin="12"/>
</StackPanel>
</Popup>
How does one make the background on Popup transparent (or any color)?
You need to set the AllowsTransparency="True" Popup Property to True
Here is an example:
<Grid>
<StackPanel>
<Button Click="Button_Click" Width="100" Height="20" Content="Click" />
<Popup x:Name="popup" Width="100" Height="100" AllowsTransparency="True">
<Grid Background="Transparent">
<TextBlock Text="Some Text" />
</Grid>
</Popup>
</StackPanel>
</Grid>
and the click handler
private void Button_Click(object sender, RoutedEventArgs e)
{
popup.Visibility = System.Windows.Visibility.Visible;
popup.IsOpen = true;
}
The base color of a Popup, or a Window for that matter, is black. You rarely see it for a Window because Window has a Background property and it defaults to a solid color, but if you set Window.Background to Transparent it will also be black. But Popup doesn't have a Background property and so, pardon the pun, this problem "pops up".
If you want the Popup to be transparent, you need to set AllowsTransparency="True". However, if you want the Popup to be a solid color, the simplest approach is to make the child of the Popup a Panel that supports the Background property and set that property to the color you desire and then set the child of the Panel to be the content you intended for the Popup in the first place. I suggest Grid as it won't affect the layout of your Popup. It's only effect will be to give you the background color you desire.
Make sure that the allow transparency is set to true, vertical and horizontal alignments are centered, and the height and width are set to Auto.
For example:
<Popup Name="popup1" Placement="Top" PlacementTarget="{Binding ElementName=button2}" AllowsTransparency="True" Height="Auto" Width="Auto" Panel.ZIndex="1" HorizontalOffset="-5" HorizontalAlignment="Center" VerticalAlignment="Center">
<StackPanel Height="92" HorizontalAlignment="Left" Margin="93,522,0,0" Name="stackPanelPop" VerticalAlignment="Top" Width="147">
</StackPanel>
</Popup>
Another possible cause:
using IsOpen="True" in markup before AllowTransparency="True"
Switching the order fixes it.
My guess is that the CircularProgressBar is actually causing the Black background. The only other way that this could happen is if there was a Style or something set on one of the controls (Popup or StackPanel or...).
Here is a quick-n-dirty example that shows a TextBlock in a popup when a checkbox is checked. The colors chosen are just to make sure things stand out visually:
<StackPanel x:Name="stackPanelLayout">
<StackPanel.Background>
<RadialGradientBrush Center="0.75, 0.75"
SpreadMethod="Reflect">
<GradientStop Color="LightBlue" Offset="0" />
<GradientStop Color="SeaGreen" Offset="0.5" />
<GradientStop Color="MidnightBlue" Offset="0.75" />
</RadialGradientBrush>
</StackPanel.Background>
<CheckBox x:Name="chkShowPopup"
FontSize="20"
Foreground="White"
Content="Show Popup" />
<Popup PlacementTarget="{Binding ElementName=stackPanelLayout}"
Placement="Center"
IsOpen="{Binding ElementName=chkShowPopup, Path=IsChecked}"
Name="m_popWaitNotifier"
PopupAnimation="Slide"
AllowsTransparency="True">
<StackPanel Orientation="Vertical" Background="Transparent">
<TextBlock Foreground="White" FontSize="30" FontWeight="Bold" Text="PopUp" />
</StackPanel>
</Popup>
</StackPanel>
So, two tests you can do to determine what is happening:
Replace the CircularProgressBar with a simple TextBlock or other control that you don't have a Style applied to.
Put the CircularProgressBar as a standalone control somewhere on your window, or on an otherwise blank test Window.
As per this article Why is my WPF Popup black and how do I get it positioned properly?
:
You need to set the AllowsTransparency property on the Popup to True, and set the PlacementTarget and Placement properties to control the position the Popup opens in.
As per the code in question:
<Popup PlacementTarget="{Binding ElementName=parentStackPanel}" Placement="Center" IsOpen="False" Name="m_popWaitNotifier" PopupAnimation="None" AllowsTransparency="False">
<StackPanel Orientation="Vertical" Background="Transparent">
<uc:CircularProgressBar x:Name="CB" StartupDelay="0" RotationsPerMinute="20" Height="25" Foreground="White" Margin="12"/>
</StackPanel>
</Popup>
the PlacementTarget is set to parentStackPanel, whereas the questioner has mentioned:
Hi Svetlozar: I tried this but it does
not work. For me though I do not have
a StackPanel outside the Popup, but I
have a StackPanel within the Popup
that holds a couple of control on it
The problem could be that Popup could not find the PlacementTarget 'parentStackPanel' because it does not exist.
The problem is that the grid is not orientation places it outside of the popup.
Remove VerticalAlignment and horizontalAlignment from all the controls inside the popup, and it will work correctly
Quite old, but may help someone: Add InitializeComponent(); in the constructor, it solved my problem:
class MyPopupClass : Popup {
/*
...
*/
public MyPopupClass () {
InitializeComponent();
/*
...
*/
}
/*
...
*/
}

Silverlight: Applying datacontext to an element within a style

I have defined a style in app.xaml. This style contains several text TextBlocks which I would like to controle as I apply the style to an object, in this case a UserPin.
How can I access these TextBlocks runtime?
I get the style by:
Style = Application.Current.Resources["UserPin"] as Style;
The style looks like this:
<Style x:Name="UserPin" TargetType="RRML_UserControls:UserPin" >
<Setter Property="RenderTransformOrigin" Value="0.5,0.5" />
<Setter Property="AnchorPoint" Value="0.5,0.5" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RRML_UserControls:UserPin">
<Grid Height="71.969" Width="Auto">
<Grid.RenderTransform>
<ScaleTransform x:Name="PART_PinScale" />
</Grid.RenderTransform>
<Grid.RowDefinitions>
<RowDefinition Height="29"/>
<RowDefinition Height="16"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.247*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="0.753*"/>
</Grid.ColumnDefinitions>
<Image Height="Auto" Source="Resources/Users.png" x:Name="PART_imgUser" VerticalAlignment="Top" Stretch="Uniform" Margin="0,0,0,0" Grid.Column="1">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
<TextBlock HorizontalAlignment="Center" Margin="0,0,0,0" Width="Auto" Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="1" TextWrapping="Wrap" VerticalAlignment="Center" TextAlignment="Center" x:Name="txtBottom" Text="{Binding Mode=OneWay, Path=LocationName}">
<TextBlock.DataContext>
<RRML_RRMLServiceReference:Location LocationName="Initial Name"/>
</TextBlock.DataContext>
</TextBlock>
<TextBlock HorizontalAlignment="Right" Margin="0,0,0,0" VerticalAlignment="Center" Text="L" TextWrapping="Wrap"/>
<TextBlock Margin="0,0,0,0" Text="R" TextWrapping="Wrap" d:LayoutOverrides="Width, Height" Grid.Column="2" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The TextBlock value I'm trying to set is txtBottom.
As you can see I have tried to apply a datacontext and a databinding to the field. This works, but all objects get the value "Initial Name" of course.
My questions are:
how can I apply my datacontext so txtBottom.Text changes, or
how can I change the value of the TextBlock named txtBottom without databinding?
in short can I access these fields or properties at all?
Runtime :)
So far I have found that Triggers may be used only in WPF.
I think of something like this:
var styledobject = new NiceObject();
styledobject.Style = Application.Current.Resources["UserPin"] as Style;
styledobject.DataContext = locationData;
Where locationData is my object containing data.
If anyone wonders; I am placing icons on a map and want to name them.
You should not explicitly apply DataContext on the TextBlock. DataContext is inherited by child FrameworkElements. You should try to set data context explicitly as little and as high up the Visual Tree as possible (for your own sanity's sake :-))
If this is a custom control, you can override on the OnApplyTemplate method and use the GetTemplateChild(string name) to retrieve references to named elements within your control.
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
TextBlock txtBottom = GetTemplateChild("txtBottom") as TextBlock;
}
Externally, if you must, you can imperatively access that specific control at runtime using an extension method to traverse the Visual Tree to find it by name.
public static T FindChild<T>(this DependencyObject element, string name)
where T : FrameworkElement
{
//Code to find the control
}

Resources