i am trying to show the current sysdatetime in Top App bar and i was wondering anyway i can do that in XAML for win store apps.
public class MainViewModel : INotifyPropertyChanged
{
private readonly DispatcherTimer _timer = new DispatcherTimer();
private string _resDateTime;
public string ResDateTime
{
get
{
return _resDateTime;
}
set
{
_resDateTime = value;
NotifyPropertyChanged("ResDateTime");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
public MainViewModel()
{
_timer.Tick += TimerOnTick;
_timer.Start();
}
private void TimerOnTick(object sender, object o)
{
ResDateTime = DateTime.Now.ToString();
}
}
add to the code behind
public MainPage()
{
this.InitializeComponent();
DataContext = new MainViewModel();
}
and put on xaml
<Page.TopAppBar>
<AppBar>
<TextBlock Text="{Binding ResDateTime}"></TextBlock>
</AppBar>
</Page.TopAppBar>
hope it will help
In your page you can set Page.TopAppBar, and Page.BottomAppBar like this:
<Page.TopAppBar>
<AppBar>
<TextBlock Text="Your text" />
</AppBar>
</Page.TopAppBar>
From there, you can whether bind the Text property, if you're using the MVVM pattern, or simply assign a value in the code behind of the page, by giving a name to the TextBlock element.
Related
I have a Label and I want to bind Text to a property of an object
public class MainCar: INotifyPropertyChanged
{
string typeCar;
public string TypeCar
{
set
{
if (typeCar != value)
{
typeCar = value;
OnPropertyChanged("TypeCar");
}
}
get
{
return typeCar;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
In my Xaml code I have a label and I do not understand how to bind Text of my Label to object`s property TypeCar
XAML CODE
<Label x:Name="label" FontSize="Large" Text="" />
BEHIND CODE
public Car_add()
{
NavigationPage.SetHasNavigationBar(this, false);
InitializeComponent();
this.BindingContext = new TypesCar();
}
VIEWMODEL CLASS
public class TypesCar
{
public TypesCar()
{
var vm = new MainCar() { TypeCar = "Ford" };
}
this is very well documented
<Label x:Name="label" FontSize="Large" Text="{Binding TypeCar}" />
then in the code behind
var vm = new MainCar() { TypeCar = "Ford" };
this.BindingContext = vm;
OR, if you are binding to a property on the SAME PAGE and NOT A VM
this.BindingContext = this;
note that if you want your UI to update as your VM changes, the VM must implement INotifyPropertyChanged
We have used DataGridTemplateColumn for our grid to display texbox under each column. We've a requirement to make the textboxes readonly if it contains any data (for data loading case). In order to achieve that, we need to access all text box controls under the radgrid. We've tried following approaches so far
Find all child controls using VisualTreeHelper - No textbox control was found
Tried with DataBindingComplete event
Is there any way to access the underlying cell's control from codebehind for RadDataGrid?
Alternative approach : Can we somehow user IsReadOnly property with some binding to check it's value and make the control readonly when value is there?
Can we somehow user IsReadOnly property with some binding to check it's value and make the control readonly when value is there?
Yes. You could certainly achieve this by using Binding. You just need to define a bool property and bind the IsReadOnly property of TextBox to this property. Then, you could change this bool value according to the text of TextBox.
Please refer to my following code sample for reference:
<telerikGrid:RadDataGrid x:Name="grid" AutoGenerateColumns="False" VerticalAlignment="Center">
<telerikGrid:RadDataGrid.Columns>
<telerikGrid:DataGridTemplateColumn Header="Country">
<telerikGrid:DataGridTemplateColumn.CellContentTemplate>
<DataTemplate>
<TextBox Text="{Binding Country}" HorizontalAlignment="Center" VerticalAlignment="Center" IsReadOnly="{Binding IsReadOnly}"/>
</DataTemplate>
</telerikGrid:DataGridTemplateColumn.CellContentTemplate>
</telerikGrid:DataGridTemplateColumn>
<telerikGrid:DataGridTemplateColumn Header="Flag">
<telerikGrid:DataGridTemplateColumn.CellContentTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Flag}" />
</StackPanel>
</DataTemplate>
</telerikGrid:DataGridTemplateColumn.CellContentTemplate>
</telerikGrid:DataGridTemplateColumn>
</telerikGrid:RadDataGrid.Columns>
</telerikGrid:RadDataGrid>
public sealed partial class MainPage : Page
{
ObservableCollection<Data> list = new ObservableCollection<Data>();
public MainPage()
{
this.InitializeComponent();
list.Add(new Data { Country = "Argentina",Flag="A"});
list.Add(new Data {Country=string.Empty,Flag="B"});
list.Add(new Data { Country = "China",Flag="C"});
this.grid.ItemsSource = list;
this.Loaded += MainPage_Loaded;
}
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
await Task.Delay(5000);
list[1].Country = "Brazil";
}
}
public class Data:INotifyPropertyChanged
{
private string _Country;
public string Country
{
get { return _Country; }
set
{
_Country = value;
if (string.IsNullOrEmpty(value))
{
IsReadOnly = true;
}
else
{
IsReadOnly = false;
}
RaisePropertyChanged("Country");
}
}
private string _Flag;
public string Flag
{
get { return _Flag;}
set
{
_Flag = value;
RaisePropertyChanged("Flag");
}
}
private bool _IsReadOnly=false;
public bool IsReadOnly
{
get { return _IsReadOnly; }
set
{
_IsReadOnly = value;
RaisePropertyChanged("IsReadOnly");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,new PropertyChangedEventArgs(PropertyName));
}
}
}
I have a very simple form that I'm using to experiment with BindableProperty. Here's the XAML for the form
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyBindableProperty"
x:Class="MyBindableProperty.MainPage">
<StackLayout>
<local:MyLabel x:Name="BindingLabel" Text="{Binding Text}" MyText="{Binding Text}"
VerticalOptions="Center"
HorizontalOptions="Center" />
<Entry x:Name="BindingEntry" Text="{Binding Text, Mode=TwoWay}"/>
<Entry x:Name="BindingEntry2" Text="{Binding Text, Mode=TwoWay}"/>
<Button x:Name="BindingButton" Text="Reset"/>
</StackLayout>
</ContentPage>
And here is the code behind
public partial class MainPage : ContentPage
{
public DataSourceClass DataSourceObject { get; set; }
public MainPage()
{
DataSourceObject = new DataSourceClass { Text = "Test1" };
BindingContext = DataSourceObject;
InitializeComponent();
BindingButton.Clicked += BindingButton_Clicked;
}
private void BindingButton_Clicked(object sender, EventArgs e)
{
var boundText = this.BindingLabel.Text;
var boundMyText = this.BindingLabel.MyText;
DataSourceObject.Text = "Test2";
}
}
Finally, here is the custom label class used in the XAML -
public class MyLabel : Label
{
public string MyText
{
get
{
return (string)GetValue(MyTextProperty);
}
set
{
SetValue(MyTextProperty, value);
}
}
public static readonly BindableProperty MyTextProperty = BindableProperty.Create(nameof(MyText), typeof(string), typeof(MyLabel), "Test", BindingMode.TwoWay, propertyChanged: MyTextChanged);
public static void MyTextChanged(BindableObject bindable, object oldValue, object newValue)
{
((MyLabel)bindable).TextChanged(newValue.ToString());
}
public void TextChanged(string newText)
{
Device.BeginInvokeOnMainThread(() => this.Text = newText);
}
}
The issues I'm having are
when the page initialises the MyTextChanged handler fires, but not after any subsequent changes
when the Reset button is clicked the value in DataSourceObject.Text is correctly updated with the value from the Entry element
no matter how I try to set the values of BindingLabel and BindingEntry2 they never reflect the values of DataSourceObject.Text after the page has loaded.
Any help would be greatly appreciated.
I stumbled across this so I updated the DataSourceClass from this
public class DataSourceClass
{
public string Text { get; set; }
}
to this
public class DataSourceClass : INotifyPropertyChanged
{
private string _text;
public string Text
{
get
{
return _text;
}
set
{
_text = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Text"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
and now everything works.
I thought BindableProperty was meant to supersede INotifyPropertyChanged?
When using touch to trigger a drag and drop action for a ListView item, it would appear that the behavior has changed between WinRT (Windows 8/8.1) and UWP (Windows 10) apps.
In WinRT, "tearing" an item to the left or right would cause it to get detached, initiating the drag behavior. In UWP, the user has to tap and hold an item for a short while, after which moving it initiates the drag action.
My question is: is there a way to revert to/implement the old WinRT-style behavior? The new way is not very obvious and in limited user testing I haven't seen one person work it out without having it explained to them.
As a quick example, the following XAML works for both WinRT and UWP, however the touch-based interactions are much discoverable in WinRT.
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView AllowDrop="True" CanReorderItems="True">
<ListView.Items>
<x:String>Item 1</x:String>
<x:String>Item 2</x:String>
<x:String>Item 3</x:String>
<x:String>Item 4</x:String>
<x:String>Item 5</x:String>
</ListView.Items>
</ListView>
</Grid>
I wanted similar behaviour that was questioned here as I was annoyed with the default win10 behaviour. There might be better solutions, but this one is what I came up.
<GridView Name="MySourceGridView" ItemsSource="{x:Bind Animals}" ScrollViewer.VerticalScrollMode="Disabled" >
<GridView.ItemTemplate>
<DataTemplate x:DataType="data:Animal">
<StackPanel Margin="20" Width="200" Height="200" PointerPressed="StackPanel_PointerPressed" DragStarting="StackPanel_DragStarting">
<StackPanel.Background>
<SolidColorBrush Color="{x:Bind Color}" />
</StackPanel.Background>
<TextBlock Text="{x:Bind Name}" />
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
Above is my GridView and binded data. I noticed that if I use gridviews candrop and dragstarted events, I just couldn't do what I liked. So I used datatemplates stackpanels pointerpressed, which launches immediatly on touch.
private async void StackPanel_PointerPressed(object sender, PointerRoutedEventArgs e)
{
var obj = (StackPanel)sender;
if (obj != null)
{
var pointerPoint = e.GetCurrentPoint(sender as UIElement);
await obj.StartDragAsync(pointerPoint);
}
}
There you have the pointerPoint too. The dragstarted on the stackpanel to move the data.
private void StackPanel_DragStarting(UIElement sender, DragStartingEventArgs args)
{
var senderElement = sender as FrameworkElement;
var ani = (Animal)senderElement.DataContext;
args.Data.SetText(ani.ID.ToString());
args.Data.RequestedOperation = DataPackageOperation.Copy;
}
Rest is just the normal data catching after I managed to pass the ID of the Animal in my list of animals forward.
private void MyTargetRectangle_DragEnter(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Copy;
e.DragUIOverride.Caption = "Kokeiles";
e.DragUIOverride.IsCaptionVisible = true;
e.DragUIOverride.IsContentVisible = true;
e.DragUIOverride.IsGlyphVisible = false;
}
private async void MyTargetRectangle_Drop(object sender, DragEventArgs e)
{
var droppedAnimalId = await e.DataView.GetTextAsync();
Animal ani = Animals.Where(p => p.ID == int.Parse(droppedAnimalId)).FirstOrDefault();
MyTargetRectangle.Fill = new SolidColorBrush(ani.Color);
}
I hope this helps someone and is not too long answer.
I've finally figured out how to get back the old Windows 8.1 behavior for the ListView. It still allows Scrolling with touch and starts a drag operation of one item if you swipe perpendicularly to the scroll axis. It's based on the Comet library and is implemented by a custom ListView. The idea is to allow TranslateX/TranslateY and System Manipulations in the ListViewItem. For this you need to override the default ListViewItem's style.
If you want to use the control, you have to bear in mind a few things:
Copy the styles in Themes/Generic.xaml and adapt the local2 Namespace.
If you use a horizontally scrolling ListView, you must set the Orientation property of the ListView accordingly. The control doesn't detect the used ItemsPanel.
You can still use the regular UWP drag & drop mechanism, but you must subscribe to a second Event called ItemStartDragging for the old Windows 8.1 style dragging.
If you handle the Drop event when using the 8.1 style dragging, the data can be found in DragEventArgs.DataView, whereas it could be found in DragEventArgs.Data.GetView() when using DragItemStarting (=default event). Don't know why they behave differently.
The styles are very basic. You might want to change them and make them more akin to the original ListViewItem styles.
Here's the code:
public class DraggingListView : ListView
{
public DraggingListView()
{
}
protected override DependencyObject GetContainerForItemOverride()
{
if (Orientation == Orientation.Horizontal)
return new HorizontalDraggingListItem(this);
else
return new VerticalDraggingListItem(this);
}
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
(element as DraggingListItem).DataContext = item;
(element as DraggingListItem).MouseSlidingEnabled = MouseSlidingEnabled;
}
public event EventHandler<ListItemStartDraggingEventArgs> ItemStartDragging;
public void OnChildItemDragged(DraggingListItem item, Windows.ApplicationModel.DataTransfer.DataPackage data)
{
if (ItemStartDragging == null)
return;
ItemStartDragging(this, new ListItemStartDraggingEventArgs(data, item.DataContext));
}
public Orientation Orientation
{
get { return (Orientation)GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
public static readonly DependencyProperty OrientationProperty =
DependencyProperty.Register("Orientation", typeof(Orientation), typeof(DraggingListView), new PropertyMetadata(Orientation.Vertical));
/// <summary>
/// Gets or sets the ability to slide the control with the mouse. False by default
/// </summary>
public bool MouseSlidingEnabled
{
get { return (bool)GetValue(MouseSlidingEnabledProperty); }
set { SetValue(MouseSlidingEnabledProperty, value); }
}
public static readonly DependencyProperty MouseSlidingEnabledProperty =
DependencyProperty.Register("MouseSlidingEnabled", typeof(bool), typeof(DraggingListView), new PropertyMetadata(false));
}
public class ListItemStartDraggingEventArgs : EventArgs
{
public Windows.ApplicationModel.DataTransfer.DataPackage Data { get; private set; }
public object Item { get; private set; }
public ListItemStartDraggingEventArgs(Windows.ApplicationModel.DataTransfer.DataPackage data, object item)
{
Data = data;
Item = item;
}
}
public class HorizontalDraggingListItem : DraggingListItem
{
public HorizontalDraggingListItem(DraggingListView listView) : base(listView)
{
this.DefaultStyleKey = typeof(HorizontalDraggingListItem);
}
protected override bool DetectDrag(ManipulationDelta delta)
{
return Math.Abs(delta.Translation.Y) > 2;
}
}
public class VerticalDraggingListItem : DraggingListItem
{
public VerticalDraggingListItem(DraggingListView listView) : base(listView)
{
this.DefaultStyleKey = typeof(VerticalDraggingListItem);
}
protected override bool DetectDrag(ManipulationDelta delta)
{
return Math.Abs(delta.Translation.X) > 2;
}
}
[TemplatePart(Name = PART_CONTENT_GRID, Type = typeof(Grid))]
public abstract class DraggingListItem : ListViewItem
{
const string PART_CONTENT_GRID = "ContentGrid";
private Grid contentGrid;
private DraggingListView _listView;
public DraggingListItem(DraggingListView listView)
{
_listView = listView;
this.DragStarting += OnDragStarting;
}
private void OnDragStarting(UIElement sender, DragStartingEventArgs args)
{
_listView.OnChildItemDragged(this, args.Data);
}
protected override void OnApplyTemplate()
{
contentGrid = this.GetTemplateChild(PART_CONTENT_GRID) as Grid;
contentGrid.ManipulationDelta += ContentGrid_ManipulationDelta;
contentGrid.ManipulationCompleted += ContentGrid_ManipulationCompleted;
contentGrid.PointerPressed += ContentGrid_PointerPressed;
base.OnApplyTemplate();
}
private PointerPoint pp = null;
private void ContentGrid_PointerPressed(object sender, PointerRoutedEventArgs e)
{
if (!MouseSlidingEnabled && e.Pointer.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
return;
pp = e.GetCurrentPoint(sender as UIElement);
}
private void ContentGrid_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
{
if (!MouseSlidingEnabled && e.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
return;
pp = null;
}
private async void ContentGrid_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
if (!MouseSlidingEnabled && e.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
return;
if (DetectDrag(e.Delta) && pp != null)
{
var pointer = pp;
pp = null;
await StartDragAsync(pointer);
}
}
protected abstract bool DetectDrag(ManipulationDelta delta);
#region Dependency Properties
/// <summary>
/// Gets or sets the ability to slide the control with the mouse. False by default
/// </summary>
public bool MouseSlidingEnabled
{
get { return (bool)GetValue(MouseSlidingEnabledProperty); }
set { SetValue(MouseSlidingEnabledProperty, value); }
}
public static readonly DependencyProperty MouseSlidingEnabledProperty =
DependencyProperty.Register("MouseSlidingEnabled", typeof(bool), typeof(DraggingListItem), new PropertyMetadata(false));
#endregion
}
And this is the XAML in Generic.xaml:
<Style TargetType="local2:HorizontalDraggingListItem" >
<Setter Property="VerticalAlignment" Value="Stretch"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local2:HorizontalDraggingListItem">
<Grid ManipulationMode="TranslateY,System" x:Name="ContentGrid" Background="{TemplateBinding Background}">
<ContentPresenter />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="local2:VerticalDraggingListItem" >
<Setter Property="HorizontalAlignment" Value="Stretch"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local2:VerticalDraggingListItem">
<Grid ManipulationMode="TranslateX,System" x:Name="ContentGrid" Background="{TemplateBinding Background}">
<ContentPresenter />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
In WinRT, "tearing" an item to the left or right would cause it to get detached, initiating the drag behavior. In UWP, the user has to tap and hold an item for a short while, after which moving it initiates the drag action.
Yes, the Behavior to start Drag action has been changed in UWP app.
My question is: is there a way to revert to/implement the old WinRT-style behavior?
The possible way is to create a Drag Behavior and attach to ListView, in this Behavior, we can handle the related touch event and use UIElement.StartDragAsync method to initiates a drag-and-drop operation programmatically, to find the current ListViewItem,
public class FrameworkElementDragBehavior : DependencyObject, IBehavior
{
private bool isMouseClicked = false;
public DependencyObject AssociatedObject { get; private set; }
public void Attach(DependencyObject associatedObject)
{
var control = associatedObject as Control;
if (control == null)
throw new ArgumentException(
"FrameworkElementDragBehavior can be attached only to Control");
AssociatedObject = associatedObject;
((FrameworkElement)this.AssociatedObject).Holding += FrameworkElementDragBehavior_Holding;
((FrameworkElement)this.AssociatedObject).DragStarting += FrameworkElementDragBehavior_DragStarting;
}
private void FrameworkElementDragBehavior_Holding(object sender, Windows.UI.Xaml.Input.HoldingRoutedEventArgs e)
{
//Just for example, not the completed code
var obj = ((ListView)sender).SelectedItem as ListViewItem;
if (obj != null)
{
//Call the UIElement.StartDragAsync method
}
}
private void FrameworkElementDragBehavior_DragStarting(UIElement sender, DragStartingEventArgs args)
{
throw new NotImplementedException();
}
public void Detach()
{
AssociatedObject = null;
}
}
I've been trying my hand at creating a simple user control with dependencyproperty and binding it, but it doesn't seem to work, not sure why. I'll just dive straight into code, please ignore the fact that the control doesn't make sense, it's just for illustrative purposes (written in WP8 if that matters).
My simple user control, it's basically a line with a property to turn it off or on.
<Grid x:Name="LayoutRoot" Background="Transparent">
<Line Height="105" Width="105" X2="100" Y2="100" Visibility="{Binding LineVisible}" Stroke="#FFFC1515" StrokeThickness="5"/>
</Grid>
public partial class SimpleUserControl : UserControl
{
public SimpleUserControl()
{
InitializeComponent();
DataContext = this;
}
public static readonly DependencyProperty LineVisibleProperty = DependencyProperty.Register("LineVisible", typeof(bool), typeof(SimpleUserControl), new PropertyMetadata(new PropertyChangedCallback(OnLineVisibleChanged)));
public bool LineVisible
{
get { return (bool)GetValue(LineVisibleProperty); }
set { SetValue(LineVisibleProperty, value); }
}
private static void OnLineVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
bool newvalue = (bool)e.NewValue;
Visibility vis = newvalue ? Visibility.Visible : Visibility.Collapsed;
(d as SimpleUserControl).Visibility = vis;
}
}
The test app
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<uc:SimpleUserControl LineVisible="{Binding class1.Vis}"/>
</Grid>
public partial class MainPage : PhoneApplicationPage
{
public Class1 class1 { get; set; }
public MainPage()
{
InitializeComponent();
DataContext = this;
}
private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e)
{
class1 = new Class1() { Vis = false };
}
}
The class1 that it's bound to
public class Class1 : INotifyPropertyChanged
{
private bool _vis;
public bool Vis
{
get { return _vis; }
set
{
_vis = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Vis"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
It doesn't seem to work, however, if it is set explicitly like below it works.
<uc:SimpleUserControl LineVisible="False"/>
I'm sure it's something simple, but I'm not seeing it.
Thanks for any help.
The problem was I was setting the DataContext = this in the UserControl and when binding to Vis in the testapp, it would override and search for Vis in the UserControl (which of course does not exist there). I did see binding errors in the debug output window which confirms this. The solution was to set the LayoutRoot of the UserControl to this as was mentioned in the link I posted earlier.
The Visibility property of WPF controls does not use bool values, it requires the Visibility enum. Thus you have two options:
Change LineVisibiltyProperty to Visibility instead of bool.
Use a converter to bind to bool and convert to Visibility.
I would suggest using the second option as this in my opinion is the better solution.
This might be helpful.