<Window.Resource>
<ResourceDictionary>
<local:SomeResourceWithObsCollection x:Key="MyItemWithCollection">
<local:SomeClass.Instance /> <!-- THIS DOES NOT WORK -->
</local:SomeResourceWithObsCollection>
</ResourceDictionary>
</Window.Resources>
I don't know how to get that line to work... I've tried doing <x:Static SomeClass.Instance />, but that also isn't allowed.
[ContentProperty("TheItems")]
public class SomeResourceWithObsCollection
{
public class SomeResourceWithObsCollection()
{
TheItems = new ObservableCollection<IMyInterface>();
}
public ObservableCollection<IMyInterface> TheItems { get; set; }
}
public class SomeClass : IMyInterface
{
private static SomeClass _instance = new SomeClass();
private SomeClass() { }
public SomeClass Instance { get { return _instance; } }
}
You can't do what you're asking to do in XAML as of right now. Perhaps future versions of XAML will account for this. You have to do it in the code behind, here is an example:
Adding a static object to a resource dictionary
The closest I can suggest is a combination of the CompositeCollection and using ListBoxItems (or some other equivalent) to wrap your static content (as I believe you can only pull static content into XAML using the {x:Static} markup extension)
This can be used in XAML as below:
<ListBox>
<ListBox.ItemsSource>
<CompositeCollection>
<ListBoxItem Content="{x:Static local:Example.One}" />
<ListBoxItem Content="{x:Static local:Example.Two}" />
</CompositeCollection>
</ListBox.ItemsSource>
</ListBox>
Related
Why does intellisense filter out interfaces and abstract classes? If I set DataType to an abstract class, it seems to still work fine. Perhaps this is just a bug? Also, related, inside DataTemplate, when I try to {x:Bind} it filters out inherited properties, so if I have Item : Base, and Base has a property Name, and DataType="Item", it filters out property Name and if I use it anyway, it seems to resolve to the class name. Did I miss something in the docs? Should I be making special non-abstract wrapping classes for every type I want to bind to xaml controls?
After my testing, it seems that inherited interface-properties are not recognized by the compiler when using the X:Bind. But it applies to abstract classes.
You could follow the sample to check your steps.
XAML code:
<ListView x:Name="List" ItemsSource="{x:Bind Fruits}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:Fruit">
<TextBlock Text="{x:Bind price}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Code behind:
public sealed partial class MainPage : Page
{
public ObservableCollection<Fruit> Fruits{get;set;}
public MainPage()
{
this.InitializeComponent();
Fruits = new ObservableCollection<Fruit>()
{
new Fruit(){name="apple",price=12},
new Fruit(){name="peach",price=15},
new Fruit(){name="pear",price=8},
new Fruit(){name="banana",price=31},
new Fruit(){name="grape",price=5}
};
}
}
public class Fruit: IFruit
{
public string name { get; set;}
}
public abstract class IFruit
{
public int price { get; set;}
}
I am new to Xamarin. I have a requirement where I have to implement a ListView or say tableView that have multiple different type-size cells.
And I also have to add Header for a particular section of cells, and some of my custom cells have a horizontal scroll in it.
I have done this thing in iOS native UITableView before, but don't know how this done in Xamarin cross platform, can anyone help me out this?
You are looking for DataTemplateSelector, which is very well documented in the official Xamarin.Forms documentation.
The basics are that you create your own DataTemplateSelector class:
public class MyDataTemplateSelector : DataTemplateSelector
{
}
In that class you override OnSelectTemplate:
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
}
By checking the type of the item argument, you should be able to figure out which template to return.
So lets say you have a ViewModel for Dog and one for Cat and want to show a different DataTemplate for each of those. You would do something like:
public class DogCatTemplateSelector : DataTemplateSelector
{
public DataTemplate DogTemplate { get; set; }
public DataTemplate CatTemplate { get; set; }
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
if (item is DogViewModel)
return DogTemplate;
return CatTemplate;
}
}
Then you can consume this in your XAML:
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="dogTemplate">
<ViewCell>
... <---- define your look of dog template here
</ViewCell>
</DataTemplate>
<DataTemplate x:Key="catTemplate">
<ViewCell>
... <---- define your look of cat template here
</ViewCell>
</DataTemplate>
<local:DogCatTemplateSelector x:Key="dogCatTemplateSelector"
DogTemplate="{StaticResource dogTemplate}"
CatTemplate="{StaticResource catTemplate}" />
</ResourceDictionary>
</ContentPage.Resources>
Then simply set the ItemTemplate to your dogCatTemplateSelector instance you've defined in the resources on your ListView:
<ListView ItemsSource="{Binding DogsCatsCollection}" ItemTemplate="{StaticResource dogCatTemplateSelector}" />
Your ViewModel would then look something like:
public class Animal : INotifyPropertyChanged
{
}
public class DogViewModel : Animal
{
}
public class CatViewModel : Animal
{
}
public class MainViewModel : INotifyPropertyChanged
{
public ObservableCollection<Animal> DogsCatsCollection { get; }
= new ObservableCollection<Animal>();
}
Then you just populate DogsCatsCollection with instances of dogs and cats.
Question about binding in XAML with WP8.
In my App.cs I declare a public property for class Setting. In other xaml pages I need to access that propery and pass that property to a ConverterParameter. I can't say I've found a clean way of doing this. Below is my current method of how I accomplish this, but it just feels dirty. Any other ways out there?
So what's happening with code below? In app the settings data gets loaded. Any time the settings gets loaded or the a setting changes it Removes/Adds App.Current.Resource. This then allows me to data bind it {StaticResource {resourceName}}
Again, this works 100%...but is there a better/another way to accomplish this?
App.cs
private static Settings _settings = null;
public static Settings Settings
{
get { return _settings; }
private set { _settings = value; }
}
private async void Application_Launching(object sender, LaunchingEventArgs e)
{
if (Settings == null)
Settings = await FlightPath.Core.Data.LoadSettingsAsync();
App.Current.Resources.Add("Settings", App.Settings);
Settings.SettingsChanged += Settings_SettingsChanged;
}
private void Settings_SettingsChanged(object sender, EventArgs e)
{
if (App.Current.Resources["Settings"] == null)
App.Current.Resources.Add("Settings", App.Settings);
else
{
App.Current.Resources.Remove("Settings");
App.Current.Resources.Add("Settings", App.Settings);
}
}
Application Page XAML using Converter / ConverterParameter
<TextBlock Text="{Binding observation_time,
Converter={StaticResource ZuluToLocalTimeConverter},
ConverterParameter={StaticResource Settings}}"
Style="{StaticResource PhoneTextNormalStyle}"
Margin="-4,0,0,0"/>
if you are using MVVM you can Create a SettingManager class which having a Singleton instance. Then declare its propert in ViewModelBase class. Finally use it into your xaml code
XAML
C#
class ViewModelBaseClass: InotifyPropertyChanged
{
public SettingManager Settings{get{return SettingManager.Instance;}}
}
class SettingManager
{
public static Instance{get{...}}
public string this[string sName]
{
return "whatever you need";
}
}
class MYViewModel: ViewModelBase
{
}
i was searching about how to binding html in webview and i found this:
public static class WebBrowserHelper
{
public static readonly DependencyProperty HtmlProperty = DependencyProperty.RegisterAttached(
"Html", typeof(string), typeof(WebBrowserHelper), new PropertyMetadata(null, OnHtmlChanged));
public static string GetHtml(DependencyObject dependencyObject)
{
return (string)dependencyObject.GetValue(HtmlProperty);
}
public static void SetHtml(DependencyObject dependencyObject, string value)
{
dependencyObject.SetValue(HtmlProperty, value);
}
private static void OnHtmlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var browser = d as WebView;
if(browser == null)
return;
var html = e.NewValue.ToString();
browser.NavigateToString(html);
}
}
and the xamls code should be that
<WebView Grid.Column="1" Height="628" Margin="10,0" VerticalAlignment="Top" cxi:WebBrowserHelper.Html="{Binding Question.Body}" />
but i can't acces this property in xaml, am i doing something wrong?
I see you're following the sample listed here.
Without seeing your full XAML listing, I'm going to guess that you don't have a namespace declaration for the cxi namespace. You probably copied the code from the page and pasted it into your own class that's in your own namespace. You need to make sure you have a namespace prefix defined for the namespace where this class resides before you can use it.
Lets say you defined WebBrowserHelper in the 'MyStuff' namespace. You would use:
xmlns:ms="using MyStuff"
At the top of your xaml file. Then later you would use
ms:WebBrowserHelper.Html
So you'd use the ms prefix instead of the cxi prefix.
Dev support, design support and more awesome goodness on the way: http://bit.ly/winappsupport
I am trying to share a ViewModel between XAML windows. This is necessary to allow multiple views of the object instance to receive events from the ViewModel.
Specifying the ViewModel as a resource in the XAML, then overwriting it in an alternate constructor does not work. The binding will still be to the default instance created in the default constructor and will not receive events from or update the proper instance.
This does not work:
MyWindow.xaml:
<Window x:Class="MyNamespace.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyNamespace"
Title="My Window"
Width="700" Height="550">
<Window.Resources>
<local:MyViewModel x:Key="MyModel"/>
</Window.Resources>
<ContentPresenter Content="{StaticResource MyModel}"/>
</Window>
MyWindow.xaml.cs
imports ...;
namespace MyNamespace {
public partial class MyWindow {
public MyWindow() {
InitializeComponent();
}
public MyWindow(MyViewModel model)
: this() {
Resources["MyModel"] = model;
}
}
}
Nor will this:
MyWindow.xaml.cs
imports ...;
namespace MyNamespace {
public partial class MyWindow {
public MyWindow()
: this(new MyViewModel()) { }
public MyWindow(MyViewModel model) {
Resources["MyModel"] = model; // Resources not yet initialized!
InitializeComponent();
}
}
}
if you are using Microsoft.Practices.Unity you can use TransientLifetimeManager.It will make sure that only one object of your viewmodel is created.
MyThis can be done by using properties on the code-behind and using the Binding tag in the XAML rather than StaticResource as follows:
MyWindow.xaml:
<Window x:Class="MyNamespace.MyWindow"
x:Name="this"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyNamespace"
Title="My Window"
Width="700" Height="550">
<ContentPresenter Content="{Binding MyModel, ElementName=this}"/>
</Window>
MyWindow.xaml.cs
imports ...;
namespace MyNamespace {
public partial class MyWindow {
public MyViewModel MyModel { get; private set; }
public MyWindow()
: this(new MyViewModel()) { }
public MyWindow(MyViewModel model) {
MyModel = model;
InitializeComponent();
}
}
}
Multiple windows (or other components) can use the same model instance.
Edit 06-Dec-12:
The XAML was not correct and the binding would not work. Added the x:Name attribute to the root element (Window), and added the ElementName argument to the Content attribute of the bound element (ContentPresenter).