For some reason I can't use any binding with a UWP Xaml SwipeItem Control. I've tried it in many different ways and with different SwipeItem properties but every time it is null. What's even stranger is any type of x:Bind to any property and it will crash.
if anyone marks this:
SwipeItem XAML Binding ignored
as a duplicate question it isn't so don't do it or I'll freak out. That question wasn't even answered.
<SwipeControl>
<SwipeControl.LeftItems>
<SwipeItems Mode="Execute">
<SwipeItem Text="{Binding}" Background="{StaticResource MIIGreen}" BehaviorOnInvoked="Close"/>
</SwipeItems>
</SwipeControl.LeftItems>
<SwipeControl.RightItems>
<SwipeItems Mode="Execute">
<SwipeItem Background="{StaticResource MIIRed}" BehaviorOnInvoked="Close" Command="{StaticResource CommandEnclosureNotInstalled}" CommandParameter="{Binding}"/>
</SwipeItems>
</SwipeControl.RightItems>
</SwipeControl>
the DataContext is just a simple DataModel and all other controls are binding fine. the command is from a staticresource and the command is firing just fine. in this example any combination of Binding or x:Bind either does nothing or crashes when trying to bind ANYTHING to Text or CommandParamter properties. There has to be something wrong with SwipItem controls, I need a way to pass the DataContext through the CommandParameter.
SwipeControl is not a standard itemControl, it does not have a dataTemplate, so SwipeItem can't find the DataContext of the parent view, so you can't directly use Binding directly in xaml. It seems you can only use Binding in code.(Below I give example of LeftItems).
in xaml:
<SwipeControl Margin="50" LeftItems="{Binding leftItems}">
</SwipeControl>
in cs:
public SwipeItems leftItems { get; set; }
public MainPage()
{
this.InitializeComponent();
SwipeItem leftItem = new SwipeItem();
Binding myBinding = new Binding();
myBinding.Source = viewmodel;
myBinding.Path = new PropertyPath("MyText"); //the property in viewmodel
BindingOperations.SetBinding(leftItem, SwipeItem.CommandParameterProperty, myBinding);
BindingOperations.SetBinding(leftItem, SwipeItem.TextProperty, myBinding);
Binding commandBinding = new Binding();
commandBinding.Source = new FavoriteCommand(); //command class
BindingOperations.SetBinding(leftItem, SwipeItem.CommandProperty, commandBinding);
leftItems = new SwipeItems() {
leftItem
};
this.DataContext = this;
}
Related
I've got an issue where if an item is selected in a list I want it to update my items in my grid. The binding is done by:
<ScrollViewer Grid.Row="1">
<ItemsControl x:Name="RightGridItemsControl" ItemsSource="{Binding News}" ItemTemplate="{StaticResource RightGridTemplate}"/>
</ScrollViewer>
When an item, e.g. Planet is selected, I want to update the ItemsSource binding to a new list. This is specified in my DataModel.
How can I update this programmatically? I've tried something like this, but it requires a DependencyObject and can't find out what it means. This also looks like WPF rather than UWP.
`var myBinding = new Binding
{
Source = Planets,
Mode = BindingMode.OneWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
BindingOperations.SetBinding(new , ItemsControl.ItemsSourceProperty, myBinding);`
What should I put as the first item for the contstructor for 'SetBinding'?
You can set the Binding like this:
BindingOperations.SetBinding(
RightGridItemsControl, ItemsControl.ItemsSourceProperty, myBinding);
or like this:
RightGridItemsControl.SetBinding(ItemsControl.ItemsSourceProperty, myBinding);
Note also that currently there is no property path present in your Binding. If there is a News property as in your XAML, the Binding should probably look like shown below, without Mode = BindingMode.OneWay, which is the default, and without UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, which has no effect in a one-way binding.
var myBinding = new Binding
{
Source = Planets,
Path = new PropertyPath("News")
};
I have to bind dynamic the Text property for the TextBlock in the WPF application in the runtime.
Here is the code:
In xaml file
<DataTemplate x:Key="Double_View_Template">
<TextBlock
x:Name="txtDoubleViewTemplate"
HorizontalAlignment="Left"
VerticalAlignment="Center"
/>
</DataTemplate>
In C#
DataTemplate data = FindResource("Double_View_Template") as DataTemplate;
TextBlock ui = data.LoadContent() as TextBlock;
Binding binding = new Binding();
binding.Path = new PropertyPath("Mass");
BindingOperations.SetBinding(ui, TextBlock.TextProperty, binding);
DataGridTemplateColumn column = new DataGridTemplateColumn();
column.CellTemplate = data;
instrumentDataGrid.Columns.Add(column);
When run the application I see only blank lines, and the values are not shown in the Datagrid. The ItemsSource and the DataContext is correctly set.
If I set
Text="{Binding Path=Mass}"
in the xaml the data is displayed.
Any idea why in the runtime the binding is not set?
I have a stackpanel that is filled with dynamic editors. The values inside the editors (TextBoxes, DatePickers, etc) are based on a item from a listbox. I create these editors based on the class and its properties bound to the listbox.
The "rendered" XAML code would something like this:
<StackPanel Name="LeftEditorStack">
<StackPanel Name="OuterPanelFirstname">
<RadioButton Name="FirstnameEnabled"></RadioButton>
<!--or any other possible FrameWorkElement-->
<TextBox></TextBox>
</StackPanel>
</StackPanel>
The TextBox has a databinding that is bound in code behind.
editorBinding = new Binding();
editorBinding.Path = new PropertyPath(String.Format("DataContext.{0}", properties[i].Name));
editorBinding.RelativeSource = new RelativeSource() { Mode = RelativeSourceMode.FindAncestor, AncestorType = typeof(StackPanel), AncestorLevel = 1 };
//editorAttribute is a custom Attribute that contains some information about the type of the Editor, BindingProperty, Position, Size and other stuff
editor.SetBinding(editorAttribute.BindingProperty, editorBinding);
This means the Datacontext of the LeftEditorStack is the real source for the binding of the TextBox. This works fine, but when I change the DataContext of the LeftEditorStack the TextBox does not get the update. The Update is occurs inside of a SelectionChanged Event:
private void lb_left_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.LeftEditorStack.DataContext = null;
this.LeftEditorStack.DataContext = this.lb_left.SelectedItem;
}
How can I get the TextBox to change its value when the DataContext is updated? I can not use UpdateTarget from the BindingExpression because the usercontrol that contains my editors has no direct access to the dynamic editors.
Also setting the BindingMode or the UpdateSourceTrigger did not change this behaviour.
Update
As Grx70 pointed out my AncestorLevel was wrong. After I set the AncestorLevel to 2 it works fine.
My objective is to include the Label's text in an error message if the content of the Label's TextBox is not valid. During validation, when only the TextBox object is easily obtained, I would like to obtain the reference to the Label object which has had its Target property bound to that TextBox.
In other words, given the source of a binding, I would like to return or retrieve the target of that binding. The WPF BindingOperations.GetBindingExpression() and related methods require that the target object be known already.
In WPF XAML I have this:
<Label Target="{Binding ElementName=RatingTextBox}">_Rating:</Label>
<TextBox Name ="RatingTextBox"/>
In C# code-behind I tried this:
BindingExpression be = RatingTextBox.GetBindingExpression(TextBox.TextProperty);
string format = be.ParentBinding.StringFormat;
However, be.ParentBinding above is null even though my TextBox is definitely bound by the label because the hot key "[Alt]-R" works. Can my TextBox get that Label's text somehow from the C# code-behind?
If I understand correctly, you are looking for a way to automatically bind the Tooltip property of your TextBox to the Content property of whatever Label object the TextBox is a target of.
Unfortunately, to do this most easily would require a mechanism in WPF to, given the source of a binding, identify its target (or targets…a single source can be bound to multiple targets, of course). And as far as I know, no such mechanism exists as such.
However, I can think of at least a couple of different alternatives that should accomplish a similar effect:
When initializing the window, enumerate all the Label objects to find their targets, and update the targets' Tooltip properties accordingly. Either just set them explicitly, or bind the properties to the Label.Content property.
Reverse the direction the Label target is declared. I.e. create an attached property that can be used on the TextBox object, indicating which Label should target it. Then use this attached property to initialize the Tooltip property appropriate (e.g. in the attached property code, bind or set the Tooltip property, or have some other property that is also bound to the attached property and when it changes, handle the binding or setting there).
The motivation for using an attached property in the second option is to allow the label/target relationship to still be declared just once in the XAML (i.e. avoiding redundancy). It's just that the declaration occurs in the target object (i.e. the TextBox) instead of the label object.
Here are a couple of examples showing what I mean…
First option above:
XAML:
<Window x:Class="TestSO32576181BindingGivenSource.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:TestSO32576181BindingGivenSource"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label x:Name="label1" Content="_Label:" Target="{Binding ElementName=textBox1}"/>
<TextBox x:Name="textBox1"/>
</StackPanel>
</StackPanel>
</Window>
C#:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
InitTooltips(this);
}
private void InitTooltips(FrameworkElement element)
{
foreach (FrameworkElement child in
LogicalTreeHelper.GetChildren(element).OfType<FrameworkElement>())
{
Label label = child as Label;
if (label != null)
{
BindingExpression bindingExpression =
BindingOperations.GetBindingExpression(label, Label.TargetProperty);
if (bindingExpression != null)
{
TextBox textBox =
FindName(bindingExpression.ParentBinding.ElementName) as TextBox;
if (textBox != null)
{
// You could just set the value, as here:
//textBox.ToolTip = label.Content;
// Or actually bind the value, as here:
Binding binding = new Binding();
binding.Source = label;
binding.Path = new PropertyPath("Content");
binding.Mode = BindingMode.OneWay;
BindingOperations.SetBinding(
textBox, TextBox.ToolTipProperty, binding);
}
}
}
InitTooltips(child);
}
}
}
Second option above:
XAML:
<Window x:Class="TestSO32576181BindingGivenSource.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:TestSO32576181BindingGivenSource"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<StackPanel Orientation="Horizontal">
<!-- Note that the Target property is _not_ bound in the Label element -->
<Label x:Name="label1" Content="_Label:"/>
<!-- Instead, it's specified here via the attached property: -->
<TextBox x:Name="textBox1" l:TooltipHelper.TargetOf="{Binding ElementName=label1}"/>
</StackPanel>
</StackPanel>
</Window>
C#:
static class TooltipHelper
{
public static readonly DependencyProperty TargetOfProperty =
DependencyProperty.RegisterAttached("TargetOf", typeof(Label),
typeof(TooltipHelper), new PropertyMetadata(null, _OnTargetOfChanged));
public static void SetTargetOf(FrameworkElement target, Label labelElement)
{
target.SetValue(TargetOfProperty, labelElement);
}
public static Label GetTargetof(FrameworkElement target)
{
return (Label)target.GetValue(TargetOfProperty);
}
private static void _OnTargetOfChanged(
DependencyObject target, DependencyPropertyChangedEventArgs e)
{
Label oldLabel = (Label)e.OldValue,
newLabel = (Label)e.NewValue;
if (oldLabel != null)
{
BindingOperations.ClearBinding(oldLabel, Label.TargetProperty);
BindingOperations.ClearBinding(target, FrameworkElement.ToolTipProperty);
}
if (newLabel != null)
{
Binding binding = new Binding();
binding.Source = newLabel;
binding.Path = new PropertyPath("Content");
binding.Mode = BindingMode.OneWay;
BindingOperations.SetBinding(
target, FrameworkElement.ToolTipProperty, binding);
binding = new Binding();
binding.Source = target;
binding.Mode = BindingMode.OneWay;
BindingOperations.SetBinding(
newLabel, Label.TargetProperty, binding);
}
}
}
Note that in the second option, no new code is required in the window class. Its constructor can just call InitializeComponent() as usual and that's it. All of the code-behind winds up in the TooltipHelper class, which is referenced in the XAML itself.
I want to create some sort of filter, when user clicks the filter button from the app bar it will fire up a popup page with list picker in it. I've googled and tried quite a number of solutions but still cannot get it to work.
Here are my codes:
XAML (MainPageView.xaml)
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="PivotContentTemplate">
<phone:Pivot Margin="-12,0,0,0" Title="FOREX NEWS" Height="672">
<phone:PivotItem Header="filter" FontFamily="{StaticResource PhoneFontFamilySemiLight}" FontSize="32">
<StackPanel Margin="12,0,0,0">
<toolkit:ListPicker Header="currencies" SelectionMode="Multiple"
micro:Message.Attach="[Event SelectionChanged] = [Action OnCurrenciesChanged($eventArgs)]">
<sys:String>gbp</sys:String>
<sys:String>eur</sys:String>
<sys:String>usd</sys:String>
</toolkit:ListPicker>
</StackPanel>
</phone:PivotItem>
</phone:Pivot>
</DataTemplate>
<phone:PhoneApplicationPage.Resources>
...
Still inside MainPageView.xaml
<bab:BindableAppBar Grid.Row="2" Mode="Minimized">
<bab:BindableAppBarButton micro:Message.Attach="[Event Click] = [Action ShowFilter($view, $eventArgs]">
</bab:BindableAppBarButton>
</bab:BindableAppBar>
MainPageViewModel.cs
public void ShowFilter(object sender, RoutedEventArgs e)
{
var view= sender as MainPageView;
CustomMessageBox messageBox = new CustomMessageBox()
{
ContentTemplate = (DataTemplate)view.Resources["PivotContentTemplate"],
LeftButtonContent = "filter",
RightButtonContent = "cancel",
IsFullScreen = true // Pivots should always be full-screen.
};
messageBox.Dismissed += (s1, e1) =>
{
switch (e1.Result)
{
case CustomMessageBoxResult.LeftButton:
// Do something.
break;
case CustomMessageBoxResult.RightButton:
// Do something.
break;
case CustomMessageBoxResult.None:
// Do something.
break;
default:
break;
}
};
messageBox.Show();
}
public void OnCurrenciesChanged(SelectionChangedEventArgs e)
{
}
For your information, I am using Caliburn.Micro and WP Toolkit for the CustomMessageBox and ListPicker.
I received exception No target found for method OnCurrenciesChanged. I only receive the exception when I after I select few items in the list picker and click any of the buttons to save the change. Another thing is that the OnCurrenciesChanged does not get triggered at all.
I think (based on what I read so far) whenever the CustomMessageBox get called, the datacontext its operating at is no longer pointing to the MainPageViewModel thus it could not find the method. But I am not sure how to actually do this.
More details:
Exception happen after I click the left button (checkmark)
Updates
So far I have try the following:
<StackPanel Margin="12,0,0,0" DataContext="{Binding DataContext, RelativeSource={RelativeSource TemplatedParent}}"> //also tried with Self
and I also added this when I instantiate messageBox
var messageBox = new CustomMessageBox()
{
ContentTemplate = (DataTemplate)view.Resources["PivotContentTemplate"],
DataContext = view.DataContext, // added this
LeftButtonContent = "filter",
RightButtonContent = "cancel",
IsFullScreen = true
};
The idea is that when the messsagebox is created, the datacontext will be the same as when the view is instantiated. However, it seems that the datacontext does not get inherited by the PickerList
Ok so I managed to get this to work. The solution is not pretty and I think it beats the purpose of MVVM at the first place.
Based on http://wp.qmatteoq.com/first-steps-in-caliburn-micro-with-windows-phone-8-how-to-manage-different-datacontext/ , inside a template the DataContext will be different. So, I need to somehow tell ListPicker to use the correct DataContext.
The solution provided by link above doesn't work for me. I think it is because when ListPicker is called inside CustomMessageBox, MainPageViewModel is no longer available or it seems not to be able to find it as suggested by the exception. So as per above code example in the question, even if I set the correct DataContext to the CustomMessageBox, it does not get inherited somehow by the ListPicker.
Here is my solution:
var messageBox = new CustomMessageBox()
{
Name = "FilterCustomMessageBox", // added this
ContentTemplate = (DataTemplate)view.Resources["PivotContentTemplate"],
DataContext = view.DataContext,
LeftButtonContent = "filter",
RightButtonContent = "cancel",
IsFullScreen = true
};
In the XAML, I edited to this
<toolkit:ListPicker Header="currencies" SelectionMode="Multiple"
micro:Action.TargetWithoutContext="{Binding ElementName=FilterCustomMessageBox, Path=DataContext}"
micro:Message.Attach="[Event SelectionChanged] = [Action OnCurrenciesChanged($eventArgs)]">
It's ugly because both ViewModel and View need to explicitly know the Name. In WPF, you can just do something like this in the binding to inherit the DataContext of the parent/etc but this is not available for WP.
{Binding DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}}
If anyone has better workaround, do let me know!