I trying to use Element Binding in Silverlight 3 to SelectedItem of ComboBox in ToolTipService.ToolTip.
This code works:
<ComboBox x:Name="cboSource" DisplayMemberPath="Name" ToolTipService.ToolTip="{Binding ElementName=cboSource, Path=SelectedItem.Name}" Width="180" />
but this code doesn't:
<ComboBox x:Name="cboSource" DisplayMemberPath="Name" Width="180" >
<ToolTipService.ToolTip>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ElementName=cboSource, Path=SelectedItem.Code}" Margin="0,0,5,0"/>
<TextBlock Text="-" Margin="0,0,5,0"/>
<TextBlock Text="{Binding ElementName=cboSource, Path=SelectedItem.Name}"/>
</StackPanel>
</ToolTipService.ToolTip>
</ComboBox>
Name and Code are properties of item in cboSource.ItemsSource.
In first code, the Name is correctly displayed in combo's tooltip but in second code tooltip is " - ".
Any ideas ?
Ahh...fun with tooltips.
The ToolTipService is actually "rooted" at the base of the tree (if you have Mole, you can double check to verify this) - hence, it does not get it's DataContext propagated down from parent elements.
I've done hacky things to fix this behavior in the past, but they all boil down to "Code up an attached property that accepts a DataContext and forwards it along to the attached element".
Best of luck - this thing has stung me a couple of times. :)
Ooh, found a link for you: http://www.codeproject.com/Articles/36078/Silverlight-2-0-How-to-use-a-DataBinding-with-the-ToolTipService.aspx
EDIT: Try this out:
<ComboBox x:Name="cboSource" DisplayMemberPath="Name" Width="180">
<local:DataBindingTooltip.TooltipDataContext>
<Binding ElementName="cboSource"/>
</local:DataBindingTooltip.TooltipDataContext>
<local:DataBindingTooltip.Tooltip>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=SelectedItem.Code}" Margin="0,0,5,0"/>
<TextBlock Text="-" Margin="0,0,5,0"/>
<TextBlock Text="{Binding Path=SelectedItem.Name}"/>
</StackPanel>
</local:DataBindingTooltip.Tooltip>
</ComboBox>
With the following class:
public class DataBindingTooltip
{
public static readonly DependencyProperty TooltipDataContextProperty =
DependencyProperty.RegisterAttached(
"TooltipDataContext",
typeof (object),
typeof (DataBindingTooltip),
null);
public static readonly DependencyProperty TooltipProperty =
DependencyProperty.RegisterAttached(
"Tooltip",
typeof(object),
typeof(DataBindingTooltip),
new PropertyMetadata(TooltipChanged));
public static void SetTooltip(DependencyObject d, object value)
{
d.SetValue(TooltipProperty, value);
}
public static object GetTooltip(DependencyObject d)
{
return d.GetValue(TooltipProperty);
}
public static void SetTooltipDataContext(DependencyObject d, object value)
{
d.SetValue(TooltipDataContextProperty, value);
}
public static object GetTooltipDataContext(DependencyObject d)
{
return d.GetValue(TooltipDataContextProperty);
}
private static void TooltipChanged(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
if (sender is FrameworkElement)
{
var element = sender as FrameworkElement;
element.Loaded += ElementLoaded;
}
}
static void ElementLoaded(object sender, RoutedEventArgs e)
{
if (sender is FrameworkElement)
{
var element = sender as FrameworkElement;
element.Loaded -= ElementLoaded;
var tooltip = element.GetValue(TooltipProperty) as DependencyObject;
if (tooltip != null)
{
if (GetTooltipDataContext(element) != null)
{
tooltip.SetValue(FrameworkElement.DataContextProperty,
element.GetValue(TooltipDataContextProperty));
}
else
{
tooltip.SetValue(FrameworkElement.DataContextProperty,
element.GetValue(FrameworkElement.DataContextProperty));
}
}
ToolTipService.SetToolTip(element, tooltip);
}
}
}
A very simple way could be to define an additional property in the source object something
whenever a user hovers the mouse over the control, the concatenated string will be shown as a nice simple tooltip.
like this:
using System...
....
public Class Employee
{
public string Forenames {get;set;}
public string Surname {get;set;}
public string Address {get;set;}
private string tooltip;
public string Tooltip
{
get{return tooltip;}
set
{
value=Forenames + " " + Surname + "," Address ;
}
}
//... other methods to follow
}
XAML MyPage.cs code has following
public partial Class MyPage : Page
{
Public List<Employee> Employees{get;set;}
public MyPage()
{
InitiazeComponents();
Employees = new List<Employee>(); // initialise
Employees=GetEmployees();
}
public List<Employee> GetEmployees(){
..
Write code that ..returns
..
}
.. other code to follow..
}
Now in MyPage.xaml
...
<ComboBox Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="8,4,0,0" Name="cboCostCentreInvestor" ItemsSource="{Binding Employees}" ToolTipService.ToolTip="{Binding ElementName=cboCostCentreInvestor,Path=SelectedItem.Tooltip}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Style="{StaticResource stackPanelComboboxItemStyle}">
<TextBlock Text="{Binding Forenames}" Style="{StaticResource textBlockComboboxItem}" />
<TextBlock Text="{Binding Surname}" Style="{StaticResource textBlockComboboxItem}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Related
I'm trying to create a UserControl in my WPF project which I want should have a DependencyProperty that I can bind to in the parent. The project is written as MVVM and I'm using Caliburn micro.
I really want to write clean and maintainable code using MVVM, so I want my UserControls to utilize viewmodels as much as possible and code behind as little as possible.
The problem is that I'm unsuccessful in getting the binding between the parent and the UserControl viewmodel to work correctly.
MyUserControl:
public partial class MyUserControlView : UserControl
{
public MyUserControlView()
{
InitializeComponent();
// If no Datacontext is set, binding between parent property and textbox text works - one way only (set from parent)!.
// -
// If Datacontext is set to this, bindings with properties in MyUserControlView code behind works.
//DataContext = this;
// If Datacontext is set to MyUserControlViewModel, binding between MyUserControlViewModel and MyUserControlView works, but not with parent.
DataContext = new MyUserControlViewModel();
}
public string ProjectNumber
{
get { return (string)GetValue(MyUserControlValueProperty); }
set { SetValue(MyUserControlValueProperty, value); }
}
public static readonly DependencyProperty MyUserControlValueProperty =
DependencyProperty.Register("ProjectNumber", typeof(string), typeof(MyUserControlView), new PropertyMetadata(null, new PropertyChangedCallback(OnProjectNumberUpdate)));
private static void OnProjectNumberUpdate(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var view = d as MyUserControlView;
view.ProjectNumberText.Text = e.NewValue as string;
}
}
MyUserControl code behind:
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="In MyUserControl: " />
<TextBlock Text="{Binding ProjectNumber}" />
</StackPanel>
<TextBox Name="ProjectNumberText" Text="{Binding ProjectNumber, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
</StackPanel>
MyUserControl ViewModel:
public class MyUserControlViewModel : Screen
{
private string _projectNumber;
public string ProjectNumber
{
get { return _projectNumber; }
set
{
_projectNumber = value;
NotifyOfPropertyChange(() => ProjectNumber);
}
}
}
Parent view:
<StackPanel>
<local:MyUserControlView ProjectNumber="{Binding ParentProjectNumber}" />
<StackPanel Orientation="Horizontal">
<TextBlock Text="In parent: "/>
<TextBlock Text="{Binding ParentProjectNumber}" />
</StackPanel>
</StackPanel>
Parent ViewModel:
public class ShellViewModel : Screen
{
public ShellViewModel()
{
ParentProjectNumber = "Hello from parent!";
}
private string _parentProjectNumber;
public string ParentProjectNumber
{
get { return _parentProjectNumber; }
set
{
_parentProjectNumber = value;
NotifyOfPropertyChange(() => ParentProjectNumber);
}
}
}
I know I'm probably way off here, but I have no idea what to do to get the bindings to work correctly.
Is there a better way to bind between a DependencyProperty and a viewmodel? Can I put the DP in the viewmodel somehow?
Here is the entire project solution: https://github.com/ottosson/DependencyPropertyTest
don't change UserControl.DataContext from inside UserControl. it can and will create issues later.
use proper name for DP (ProjectNumberProperty and corresponding ProjectNumber) and add BindsTwoWayByDefault to metadata:
public partial class MyUserControlView : UserControl
{
public MyUserControlView()
{
InitializeComponent();
}
public string ProjectNumber
{
get { return (string)GetValue(ProjectNumberProperty); }
set { SetValue(ProjectNumberProperty, value); }
}
public static readonly DependencyProperty ProjectNumberProperty = DependencyProperty.Register
(
"ProjectNumber",
typeof(string),
typeof(MyUserControlView),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
);
}
fix bindings in xaml:
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="In MyUserControl: " />
<TextBlock Text="{Binding Path=ProjectNumber, RelativeSource={RelativeSource AncestorType=UserControl}}" />
</StackPanel>
<TextBox Text="{Binding Path=ProjectNumber, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=UserControl}}" />
</StackPanel>
that should do it.
btw, "clean and maintainable code using MVVM" and "want my UserControls to utilize viewmodels as much as possible" sort of contradict each other.
also nothing wrong with code-behind in UserControls as long as that code handles only view functionality. for example: DataGrid source code contains 8000+ LoC
I have column in DataGrid to display a text message. Unfortunately it is too long. So I custom the cell column template in a textblock use TextWrapping = "Wrap"
It displays multiple lines. I don't want it. I just want to display the first two lines, at the end adding an ellipsis(...)
Is there a way to do that?
To achieve that you need to define a custom Behavior, first make sure to add the System.Windows.Interactivity namespace ( which is part of Expression.Blend.Sdk, use NuGet to install it: Install-Package Expression.Blend.Sdk), here a basic implementation (credit goes to #Itzalive):
public class NumLinesBehaviour : Behavior<TextBlock>
{
public static readonly DependencyProperty MaxLinesProperty =
DependencyProperty.RegisterAttached(
"MaxLines",
typeof(int),
typeof(NumLinesBehaviour),
new PropertyMetadata(default(int), OnMaxLinesPropertyChangedCallback));
public static void SetMaxLines(DependencyObject element, int value)
{
element.SetValue(MaxLinesProperty, value);
}
public static int GetMaxLines(DependencyObject element)
{
return (int)element.GetValue(MaxLinesProperty);
}
private static void OnMaxLinesPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TextBlock element) element.MaxHeight = GetLineHeight(element) * GetMaxLines(element);
}
public static readonly DependencyProperty MinLinesProperty =
DependencyProperty.RegisterAttached(
"MinLines",
typeof(int),
typeof(NumLinesBehaviour),
new PropertyMetadata(default(int), OnMinLinesPropertyChangedCallback));
public static void SetMinLines(DependencyObject element, int value)
{
element.SetValue(MinLinesProperty, value);
}
public static int GetMinLines(DependencyObject element)
{
return (int)element.GetValue(MinLinesProperty);
}
private static void OnMinLinesPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TextBlock element) element.MinHeight = GetLineHeight(element) * GetMinLines(element);
}
private static double GetLineHeight(TextBlock textBlock)
{
double lineHeight = textBlock.LineHeight;
if (double.IsNaN(lineHeight))
lineHeight = Math.Ceiling(textBlock.FontSize * textBlock.FontFamily.LineSpacing);
return lineHeight;
}
}
Now let's say you have a DataGrid Bound to an ObservableCollection of TestClass with the "Name" property, a basic use of the NumLinesBehaviour Behavior is as follow:
<Window ...
xmlns:local="clr-namespace:YourNameSpace"
Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
<DataTemplate x:Key="CellTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock
Width="200"
TextWrapping="Wrap"
local:NumLinesBehaviour.MaxLines="2"
TextTrimming="WordEllipsis"
LineStackingStrategy="BlockLineHeight"
Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<DataGrid ItemsSource="{Binding DgCollection}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Name" CellTemplate="{StaticResource CellTemplate}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
Make sure to set the TextTrimming of the TextBlock to "WordEllipsis".
Update
The output looks something like that:
I have a simple class abc
class abc
{
public string a { get; set; }
public string b { get; set; }
public string c { get; set; }
public abc(string d, string e, string f)
{
a = d;
b = e;
c = f;
}
}
public MainPage()
{
InitializeComponent();
abc obj = new abc("abc1", "abc2", "abc3");
LayoutRoot.DataContext = obj;
}
and a grid which contain three textbox 1 2 3 I am trying to bind these 3 properties of a class to a grid usercontrol.
<Grid x:Name="LayoutRoot" Background="White">
<TextBox Height="27" HorizontalAlignment="Left" Margin="125,86,0,0" Name="textBox1" Text="{Binding Path= a}" VerticalAlignment="Top" Width="120" />
<TextBox Height="25" HorizontalAlignment="Left" Margin="21,192,0,83" Name="textBox2" Text="{Binding Path= b}" Width="120" />
<TextBox Height="25" HorizontalAlignment="Left" Margin="250,192,0,0" Name="textBox3" Text="{Binding Path= c}" VerticalAlignment="Top" Width="120" />
</Grid>
it doesn't show any error but it does not show any output to a screen,what specific problem it creating?
Try do not use "Path= " (with space) in the binding expression. Try use:
Text="{Binding a}"
"Path" is present hiddenly in binding expressions. You need read some resources about bindings.
First your type 'abc' should implement INotifyPropertyChanged.
public class abc : INotifyPropertyChanged
{
...
}
Then you need to raise the INotifyPropertyChanged.PropertyChanged event
private void RaiseProperty(string propertyName)
{
var handle = PropertyChanged;
if(handle != null)
{
handle(this, new PropertyChangedEventArgs(propertyName));
}
}
private string _a;
public string a { get{ return _a;} set{ _a = value; RaiseProperty("a"); } }
....
This should work as you need to a mechanism to notify the Binding if you are using CLR proprties; and that mechanism is provided by INotifyPropertyChanged interface
I have ComboBox with CheckBoxes for items.
When user checks or uncheckes boxes I want the selected values to be displayed in the ContentPresenter separated by comma.
At the the moment I have overridden ContentPresenter:
<ContentPresenter x:Name="ContentPresenter"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
ContentTemplate="{StaticResource SelectedOperationsText}"/>
ContentPresenter is a part of ComboBox style by default.
Any hints on how to implement this feature?
ComboBox ItemTemplate is implemented like this:
<DataTemplate x:Key="ComboItemTemplate">
<Grid HorizontalAlignment="Left">
<CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Text}"/>
</Grid>
</DataTemplate>
This solution isn't ideal (for example, you can create custom control template for control inherited from combobox), but it works.
Xaml
<my:MyComboBox Width="180" ItemsSource="{Binding TestItems}" Text="{Binding SelectedItemsText}">
<my:MyComboBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Left">
<CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" Content="{Binding Text}"/>
</Grid>
</DataTemplate>
</my:MyComboBox.ItemTemplate>
</my:MyComboBox>
Hack of the combobox:
public class MyComboBox : ComboBox
{
private ContentPresenter selectedContent;
public MyComboBox()
{
this.DefaultStyleKey = typeof(ComboBox);
}
public override void OnApplyTemplate()
{
this.selectedContent = this.GetTemplateChild("ContentPresenter") as ContentPresenter;
this.RefreshContent();
base.OnApplyTemplate();
this.SelectionChanged += (s, e) =>
{
//Cancel selection
this.SelectedItem = null;
this.RefreshContent();
};
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyComboBox),
new PropertyMetadata(null, new PropertyChangedCallback((s,e)=>((MyComboBox)s).RefreshContent())));
private void RefreshContent()
{
if (this.selectedContent != null)
{
var tb = (TextBlock)this.selectedContent.Content;
tb.Text = this.Text;
}
}
}
MainViewModel
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
this.InitializeTestItems();
}
public void InitializeTestItems()
{
this.TestItems = new List<TestItemModel>{
new TestItemModel{IsChecked=true, Text="first"},
new TestItemModel{IsChecked=false, Text="second"},
new TestItemModel{IsChecked=false, Text="third"}};
this.RefreshSelectedItemsText();
foreach (var item in this.TestItems)
item.CheckChanged += (s, e) => this.RefreshSelectedItemsText();
}
private void RefreshSelectedItemsText()
{
SelectedItemsText = string.Join(", ", this.TestItems.Where(ti => ti.IsChecked).Select(ti => ti.Text));
}
public List<TestItemModel> TestItems { get; set; }
private string selectedItemsText;
public string SelectedItemsText
{
get { return selectedItemsText; }
set
{
selectedItemsText = value;
OnPropertyChanged("SelectedItemsText");
}
}
}
4.ItemViewModel
public class TestItemModel
{
private bool isChecked;
public bool IsChecked
{
get { return isChecked; }
set
{
isChecked = value;
if (CheckChanged != null)
CheckChanged(this, null);
}
}
public string Text { get; set; }
public event EventHandler<EventArgs> CheckChanged;
}
I did not understand what you meant by "the ContentPresenter".
If you want a combox box, with the list of selected items as its text, I can explain how my son (who's not in SO) did it:
He put a grid with a ComboBox followed by a TextBlock. The ItemTemplate of the ComboBox includes a check box with a handler for the Checked and UnChecked events. In these events, he recomputed the Text property of the TextBlock, based on the selected state of the check boxes.
Here is the XAML:
<Grid Name="LayoutRoot">
<ComboBox ItemsSource="{Binding Path=SitesList}" Name="CBsites" DropDownOpened="ComboBox_DropDownOpened" DropDownClosed="ComboBox_DropDownClosed">
<ComboBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Path=Location}" Checked="SiteCheckBox_Checked" Unchecked="SiteCheckBox_Unchecked" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBlock Name="TXTselected" IsHitTestVisible="False" VerticalAlignment="Center" Margin="6,0,0,0" />
</Grid>
I think one can do it without the TextBlock. Hopefully, this can put you in the right direction.
I have created a codeplex project here: codeplex inspired by this blog and a number other ones, please check it out and improve it etc. Hopefully this or something like it will find it's way into the toolkit...
I prefer not needing a selection boolean in the bound data so i brought a bindable SelectedItems
say I have a ListView with an ItemControl. And a Details part that shows the selected Item from the ListView. Both are in the same xaml page. I tried everything to accomplish it, but what do I miss?
<!-- // List -->
<ItemsControl ItemsSource="{Binding Path=Model, ElementName=SomeListViewControl, Mode=Default}" SnapsToDevicePixels="True" Focusable="False" IsTabStop="False">
<ItemsControl.ItemTemplate>
<DataTemplate>
<SomeListView:SomeListItemControl x:Name=listItem/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!-- // Details -->
<Label Content="Begindatum" FontSize="16" VerticalAlignment="Center" Grid.Row="1" Margin="2,0,0,0"/>
<TextBox x:Name="Begindatum" Grid.Column="1" Grid.Row="1" Text="{Binding Path=BeginDate, ElementName=listItem,Converter={StaticResource DateTimeConverter}, ConverterParameter=dd-MM-yyyy}" IsEnabled="False" Style="{DynamicResource TextBoxStyle}" MaxLength="30"/>
public event EventHandler<DataEventArgs<SomeEntity>> OnOpenSomething;
public ObservableCollection<SomeEntity> Model
{
get { return (ObservableCollection<SomeEntity>)GetValue(ModelProperty); }
set
{
Model.CollectionChanged -= new NotifyCollectionChangedEventHandler(Model_CollectionChanged);
SetValue(ModelProperty, value);
Model.CollectionChanged += new NotifyCollectionChangedEventHandler(Model_CollectionChanged);
UpdateVisualState();
}
}
public static readonly DependencyProperty ModelProperty = DependencyProperty.Register("Model", typeof(ObservableCollection<SomeEntity>), typeof(SomeListView), new UIPropertyMetadata(new ObservableCollection<SomeEntity>(), new PropertyChangedCallback(ChangedModel)));
private static void ChangedModel(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
SomeListView someListView = source as SomeListView;
if (someListView.Model == null)
{
return;
}
CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(someListView.Model);
}
private void Model_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (Model == null)
{
return;
}
}
Do not use an ItemsControl - ItemsControl does not have a SelectedItem property - and therefore you cannot determine which one is selected.
Use a ListBox instead and then in the detail section make a binding like so: ... DataContext="{Binding SelectedItem,ElementName=ListboxName}" ... where ListboxName is the Name property of the ListBox you use.