bind properties to a listview - xaml

I have a Weather VM, that get my city and country code perfectly, but I am trying to bind the rest of my data to XAML.
All my data is store in the array, and for some reason, when I loop, the variable i, does not increment and the app crash.
I also have the problem of the icon, I have a list, that is the itemsource of my Listview, but the Icon is on another array
I tried to loop, and assign each variable, and the loop always crash
var splitedData = cityData.Split(",");
var city = splitedData[0];
var conutryCode = splitedData[1];
var data = await WeatherAPI.GetWeatherDataAsync(city, conutryCode);
if (data != null) {
for (int i = 0; i < data.list.Count; i++) {
rootObject.list[i].dt_txt = data.list[i].dt_txt;
rootObject.list[i].main.temp_max = data.list[i].main.temp_max;
rootObject.list[i].main.temp_min = data.list[i].main.temp_min;
rootObject.list[i].weather[i].icon
}
}
}
xaml listView
Margin="20" ItemsSource="{Binding rootObject.list}">
<ListView.ItemTemplate>
<DataTemplate>
<RelativePanel>
<TextBlock x:Name="dateTB"
Text="{Binding dt_txt}"
RelativePanel.RightOf="iconTB"
RelativePanel.AlignTopWith="iconTB" />
<TextBlock x:Name="highTB"
Text="{Binding main.temp_max}"
RelativePanel.RightOf="iconTB"
RelativePanel.Below="dateTB"
FontSize="10" />
<TextBlock x:Name="lowTB"
RelativePanel.RightOf="highTB"
RelativePanel.Below="dateTB"
FontSize="10"
Text="{Binding main.temp_min}"
Margin="10,0,0,0" />
<Image x:Name="iconTB"
Source="{}"
Height="30"
Width="30"
/>
</RelativePanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
I expect the Dates to appear, the High to appear and the low to appear.
Also I have don't have a clue of how to bind the icon, becouse the icon is in Weather, and not the RootObject list, that is the itemsource of my list

I tried your code in my side and find something might be the reason. The problem might be that you didn't create instances for main object or weather list or day list. So you are assigning values to null and then it gives error.
I changed it a little bit, you can try in your side.(I still can't use MapLocator.GetCityData(); so I haven't tried this with real data.)
public class RootObject : Notify
{
private List<Day> _list;
public List<Day> list
{
get { return _list; }
set
{
if (value != _list)
{
_list = value;
onPropertyChanged("list");
}
}
}
public RootObject()
{
//I added five objects for test. In real scenario, the count depends on the data number you get
list = new List<Day>();
list.Add(new Day());
list.Add(new Day());
list.Add(new Day());
list.Add(new Day());
list.Add(new Day());
}
}
public class Day : Notify
{
private Main _main;
public Main main
{
get { return _main; }
set
{
if (value != _main)
{
_main = value;
onPropertyChanged("main");
}
}
}
private List<Weather> _weather;
public List<Weather> weather
{
get { return _weather; }
set
{
if (value != _weather)
{
_weather = value;
onPropertyChanged("weather");
}
}
}
private string _dt_txt;
public string dt_txt
{
get { return _dt_txt; }
set
{
if (value != _dt_txt)
{
_dt_txt = value;
onPropertyChanged("dt_txt");
}
}
}
public Day()
{
main = new Main();
//I added five objects for test. In real scenario, the count depends on the data number you get
weather = new List<Weather>();
weather.Add(new Weather());
weather.Add(new Weather());
weather.Add(new Weather());
weather.Add(new Weather());
weather.Add(new Weather());
}
}
For local test, I just added 5 objects. In your real scenario, you need to check the count of data from bingmap.

Related

How to Bind a column with a function which take the value of another column in parameter

For now, I have something like that (2 columns with dropboxes containing values independent from each other):
<xcdg:DataGridControl.Columns>
<xcdg:Column Title="A"
FieldName="A"
CellContentTemplate="{StaticResource ADT}"
GroupValueTemplate="{StaticResource ADT}"
Converter="{StaticResource AConverter}"
CellEditor="{StaticResource AEditor}"/>
<xcdg:Column Title="B"
FieldName="B"
CellContentTemplate="{StaticResource BDT}"
GroupValueTemplate="{StaticResource BDT}"
Converter="{StaticResource BConverter}"
CellEditor="{StaticResource BEditor}"/>
</xcdg:DataGridControl.Columns>
And I would like the B column to be a dropbox containing values depending on the value selected in the first column.
I don't know how to achieve that. I read about Binding.RelativeSource but I think it is not at all what I should use.
Thanks
I can think of two ways to do that, and since you didn't provide your exact case, i will provide a simple scenario and build my answer base on it,
let say you have a DataGrid with two editable columns (A and B), in the edit mode you can choose the A value from a combobox list, and then the B combobox will be filtered to show only the items whom their value starts with the A value for example, if A="aa", B should be {"aaaa","aabb"}, to implement that you need first a Model that represent the DataGrid Items
public class GridItem
{
public String A { get; set; }
public String B { get; set; }
}
In your codebehind / ViewModel define those properties (the DataGrid , and the comboboxes ItemSource Collections) :
private ObservableCollection<GridItem> _gridItemsCollection = new ObservableCollection<GridItem>()
{
new GridItem()
{
A="aa",
B="bbbb"
}
};
public ObservableCollection<GridItem> GridItemsCollection
{
get
{
return _gridItemsCollection;
}
set
{
if (_gridItemsCollection == value)
{
return;
}
_gridItemsCollection = value;
OnPropertyChanged();
}
}
//for the first Combobox
private ObservableCollection<String> _aCollection = new ObservableCollection<String>()
{
"aa",
"bb"
};
public ObservableCollection<String> ACollection
{
get
{
return _aCollection;
}
set
{
if (_aCollection == value)
{
return;
}
_aCollection = value;
OnPropertyChanged();
}
}
//for the second Combobox
private ObservableCollection<String> _bCollection ;
public ObservableCollection<String> BCollection
{
get
{
return _bCollection;
}
set
{
if (_bCollection == value)
{
return;
}
_bCollection = value;
OnPropertyChanged();
}
}
Define a full B collection from which your B combobox's itemsource will be populated
ObservableCollection<String> MainBCollection = new ObservableCollection<String>()
{
"aaaa",
"aabb",
"bbaa",
"bbbb"
};
Finally the population of the B combobox will be based on the selected item in the A combobox using this property,
private String _selectedAItem;
public String SelectedAItem
{
get
{
return _selectedAItem;
}
set
{
if (_selectedAItem == value)
{
return;
}
_selectedAItem = value;
OnPropertyChanged();
var returnedCollection = new ObservableCollection<String>();
foreach (var val in MainBCollection)
{
if (val.StartsWith(_selectedAItem))
{
returnedCollection.Add(value);
}
}
BCollection = new ObservableCollection<string>(returnedCollection);
}
}
You need of course to implement the INotifypropertyChanged Interface, so that the B Combobox Itemsource will be updated,
Now regarding the Xaml, due to some limitations in Xceed you need to specify the Combobox's ItemSource and SelectedItem using the RelativeSource and Ancestor binding,
<Grid >
<xcdg:DataGridControl ItemsSource="{Binding GridItemsCollection}" AutoCreateColumns="False" SelectionMode="Single" >
<xcdg:DataGridControl.Columns>
<xcdg:Column Title="A"
FieldName="A"
>
<xcdg:Column.CellContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</xcdg:Column.CellContentTemplate>
<xcdg:Column.CellEditor>
<xcdg:CellEditor>
<xcdg:CellEditor.EditTemplate>
<DataTemplate>
<ComboBox Name="AComboBox" SelectedItem="{Binding SelectedAItem, RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}}" SelectedValue="{xcdg:CellEditorBinding}"
ItemsSource="{Binding RelativeSource=
{RelativeSource FindAncestor,
AncestorType={x:Type wpfApplication3:MainWindow}},
Path=ACollection}">
</ComboBox>
</DataTemplate>
</xcdg:CellEditor.EditTemplate>
</xcdg:CellEditor>
</xcdg:Column.CellEditor>
</xcdg:Column>
<xcdg:Column Title="B"
FieldName="B"
>
<xcdg:Column.CellContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</xcdg:Column.CellContentTemplate>
<xcdg:Column.CellEditor>
<xcdg:CellEditor>
<xcdg:CellEditor.EditTemplate>
<DataTemplate>
<ComboBox Name="AComboBox" SelectedValue="{xcdg:CellEditorBinding}" ItemsSource="{Binding RelativeSource=
{RelativeSource FindAncestor,
AncestorType={x:Type Window}},
Path=BCollection}">
</ComboBox>
</DataTemplate>
</xcdg:CellEditor.EditTemplate>
</xcdg:CellEditor>
</xcdg:Column.CellEditor>
</xcdg:Column>
</xcdg:DataGridControl.Columns>
</xcdg:DataGridControl>
</Grid>
and the result is something like that
The Other way to do that is by using a MultivalueConverter and update the B Collection eachtime the A SelectedValue is changed,
something like that :
<xcdg:CellEditor.EditTemplate>
<DataTemplate>
<ComboBox Name="AComboBox" SelectedValue="{xcdg:CellEditorBinding}">
<ComboBox.ItemsSource>
<MultiBinding Converter="{StaticResource BCollectionConverter}">
<Binding Path="BCollection" RelativeSource="{RelativeSource AncestorType={x:Type Window}}"/>
<Binding Path="SelectedValue" ElementName="AComboBox" />
</MultiBinding>
</ComboBox.ItemsSource>
</ComboBox>
</DataTemplate>
</xcdg:CellEditor.EditTemplate>
And implement the converter to update the B Combobox's ItemSource,
public class BCollectionConverter:IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values == null)
return null;
var bCollection = (values[0] as ObservableCollection<String>);
var aSelectedItem = (values[1] as String);
if (aSelectedItem == null)
return null;
var returnedCollection = new ObservableCollection<String>();
foreach (var value in bCollection)
{
if (value.StartsWith(aSelectedItem))
{
returnedCollection.Add(value);
}
}
return returnedCollection;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I didn't try that last one, you might as well give it a try, I hope that did help.

What is the correct property name to notify when binding to an element in an Observable collection directly?

I have a binding of the following form in XAML,
Title="{Binding SelectedNewsItems[0].Title}"
Note that it refers to a particular element in the SelectedNewsItems which is an ObservableCollection. (I have a collection of nine buttons of various sizes, each styled, and sized differently and so a more standard ListView is not appropriate.)
When I reassign SelectedNewsItems I raise a PropertyChanged event for SelectedNewsItems, however, this does not appear to cause the bindings to update for the individual bound elements and their properties. I have tried the following,
public ObservableCollection<NewsItem> _selectedNewsItems;
public ObservableCollection<NewsItem> SelectedNewsItems
{
get
{
return this._selectedNewsItems;
}
set
{
if (this._selectedNewsItems != value)
{
this._selectedNewsItems = value;
this.NotifyPropertyChanged();
for (int i = 0; i < this._selectedNewsItems.Count; i++)
{
this.NotifyPropertyChanged(String.Format("SelectedNewsItems[{0}].Content", i));
this.NotifyPropertyChanged(String.Format("SelectedNewsItems[{0}].Title", i));
this.NotifyPropertyChanged(String.Format("SelectedNewsItems[{0}].Id", i));
this.NotifyPropertyChanged(String.Format("SelectedNewsItems[{0}].Image", i));
}
}
}
}
Hmm, I cannot exacly say where your code is wrong (as I see only part of it), but maybe you haven't set your DataContex or something else. For the purpose of research I've made simple example, which works quite fine. Take a look at it and maybe it will help you:
In Xaml:
<Button x:Name="first" VerticalAlignment="Top" Content="{Binding SelectedNewsItems[0].Name}" Grid.Row="0"/>
<Button x:Name="second" VerticalAlignment="Center" Content="{Binding SelectedNewsItems[1].Name}" Grid.Row="1"/>
In code behind (I put all the code - yeah quite a lot of, but I cannot guess what is wrong with your code):
public class NewsItem
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaiseProperty(string property = null)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(property));
}
private ObservableCollection<NewsItem> _selectedNewsItems = new ObservableCollection<NewsItem>();
public ObservableCollection<NewsItem> SelectedNewsItems
{
get
{
return this._selectedNewsItems;
}
set
{
if (this._selectedNewsItems != value)
{
this._selectedNewsItems = value;
this.RaiseProperty();
for (int i = 0; i < this._selectedNewsItems.Count; i++)
{
this.RaiseProperty(String.Format("SelectedNewsItems[{0}].Name", i));
}
}
}
}
public MainPage()
{
NewsItem firstT = new NewsItem() { Name = "First" };
NewsItem secondT = new NewsItem() { Name = "Second" };
SelectedNewsItems.Add(firstT);
SelectedNewsItems.Add(secondT);
InitializeComponent();
this.DataContext = this;
first.Click += first_Click;
second.Click += second_Click;
}
private void first_Click(object sender, RoutedEventArgs e)
{
NewsItem change = new NewsItem() { Name = "Changed by First" };
SelectedNewsItems[1] = change;
}
private void second_Click(object sender, RoutedEventArgs e)
{
NewsItem change = new NewsItem() { Name = "Changed by Second" };
SelectedNewsItems[0] = change;
}
}
As I click on buttons the bindigs work, so maybe it will help you.

Is this the efficient way to display list of timers constantly updating the UI?

I am displaying a list of timers which constantly update the UI (every one second) to show proper time.
Is this the efficient way ? How this process can be improved from performance point of view ?
I am using MVVMLight toolkit for windows phone.
XAML code:
<ListBox ItemsSource="{Binding TimersCollection}"
ItemTemplate="{StaticResource SingleItemTemplate}"/>
Here is my simple itemtemplate code,It also has Pause, Add Minute button but removed from here for simplicity:
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="SingleItemTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding CurrentTime.Hours}"/>
<TextBlock Text="H"></TextBlock>
<TextBlock Text="{Binding CurrentTime.Minutes}" />
<TextBlock Text="M"></TextBlock>
<TextBlock Text="{Binding CurrentTime.Seconds}" />
<TextBlock Text="S"></TextBlock>
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
Here is my ViewModel code which is injected in view:
public class Page1VM : ViewModelBase
{
private ObservableCollection<MyTimer> _timersCollection = new ObservableCollection<MyTimer>();
public Page1VM()
{
// sample code to simulate collection of timers
for (int i = 1; i < 5; i++)
{
var t = new MyTimer();
t.TotalTimeSpan = new TimeSpan(0, i, 0);
_timersCollection.Add(t);
t.Start();
}
}
public IList<MyTimer> TimersCollection
{
get { return _ghatikatimerscoll; }
}
}
Here is ITimer Interace
public interface ITimer
{
bool Start();
bool Stop();
bool IsRunning { get; set; }
void AddMinute();
}
Its implementation
public class MyTimer : ViewModelBase, ITimer
{
public TimeSpan TotalTimeSpan { private get; set; }
private readonly DispatcherTimer _myDispatcherTimer;
private TimeSpan _startTime;
public bool IsRunning { get; set; }
public MyTimer()
{
_myDispatcherTimer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 1) };
_myDispatcherTimer.Tick += _myDispatcherTimer_Tick;
}
private TimeSpan _currentTime;
public TimeSpan CurrentTime
{
get
{
return _currentTime;
}
set
{
_currentTime = value;
RaisePropertyChanged("CurrentTime");
}
}
void _myDispatcherTimer_Tick(object sender, EventArgs e)
{
if (_myDispatcherTimer.IsEnabled)
{
var currenttime = TotalTimeSpan.Add(new TimeSpan(0, 0, 1)) - (DateTime.Now.TimeOfDay - _startTime);
CurrentTime = currenttime;
}
}
public bool Start()
{
_startTime = DateTime.Now.TimeOfDay;
if (_currentTime.TotalSeconds != 0)
{
// resuming after paused
TotalTimeSpan = CurrentTime;
}
IsRunning = true;
_myDispatcherTimer.Start();
return true;
}
public bool Stop()
{
_myDispatcherTimer.Stop();
IsRunning = false;
return true;
}
public void AddMinute()
{
TotalTimeSpan = TotalTimeSpan.Add(new TimeSpan(0, 1, 1));
}
}
Basically, I am displaying a collection of Timers on screen which updates itself. Each item in list has its own DispatcherTimer. User an click "Pause" button for each item to pause that particular timer. User can also click on "Add Minute" button which adds 1 minute to the particular item in collection.
Is this method efficient to update the UI constantly?
Rather than having one timer per item, you can declare one global dispatcher timer that will update every item every second (actually, you should set a delay lower than a second or you may see some items skipping a second). It will be much more efficient than using x dispatcher timers. You'd have to put it in the ViewModel and iterate with a foreach loop. You could also create a wrapper around the timer, define an event that will be triggered every second, and have all the items subscribe to that event, but I don't think it's worth the trouble.

Unable to use Autocompletebox in windows 8

I installed nudget autocomplete toolkit but unfortunately I found it wierd that this control doesn't have enough property to serve as autocomplete. It has ItemsSource but it doesn't show the list of items filtered when you type something. I am also looking for something like textChanged so that I can invoke my service and get the result again and bind the itemsource.
Here's my implementation used in Group Contacts:
XAML:
xmlns:Interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:behaviors="using:MyNamespace.Behaviors"
.
.
<TextBox x:Name="Searchbox" PlaceholderText="contact's name" Width="250"
IsTextPredictionEnabled="False"
IsSpellCheckEnabled="False"
VerticalAlignment="Center">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="KeyUp">
<behaviors:FilterContactAction />
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</TextBox>
Code:
public class FilterContactAction : DependencyObject, IAction
{
string _previousResult = null;
public object Execute(object sender, object parameter)
{
var textbox = sender as TextBox;
var keyEventArgs = parameter as KeyRoutedEventArgs;
var noChanges = textbox.Text == _previousResult;
var deletionOccurred = keyEventArgs.Key == VirtualKey.Back ||
keyEventArgs.Key == VirtualKey.Delete;
if (noChanges || deletionOccurred)
{
return null;
}
var viewModel = ResourceLocator.Instance[typeof(HomeViewModel)] as HomeViewModel;
viewModel.CanSearch = FindMatch(textbox, viewModel.Contacts);
return null;
}
private bool FindMatch(TextBox textbox, ObservableCollection<Contact> contacts)
{
foreach (var contact in contacts)
{
var suggestionDisplayed = DisplaySuggestion(textbox, contact);
if (suggestionDisplayed)
{
return true;
}
}
return false;
}
private bool DisplaySuggestion(TextBox textbox, Windows.ApplicationModel.Contacts.Contact contact)
{
var characterCount = textbox.Text.Count();
var suggestionDisplayed = false;
var isMatch = contact.DisplayName.ToUpper().StartsWith(textbox.Text.ToUpper());
if (isMatch)
{
textbox.Text = contact.DisplayName;
textbox.SelectionStart = characterCount;
textbox.SelectionLength = textbox.Text.Length - textbox.SelectionStart;
_previousResult = textbox.Text;
suggestionDisplayed = true;
}
return suggestionDisplayed;
}
}
TextBoxExt control from Syncfusion WinRT Studio has enough features to work as an AutoComplete. It has more than 15 suggestion modes including custom filter option. Hope this helps.
http://www.syncfusion.com/products/winrt/controls
Not sure what you used. Can't tell you why it doesn't work either. however last year I wanted AutoCompleteTextBox and ended up writing it myself.
you can find it here.
https://github.com/hermitdave/HermitDaveWinRTControls

Dynamically Create controls using ContentControl and Converters in silverlight4

I have a problem to create dynamic controls in silverlight 4.
My requirement is:
I have question table in database, which is like below.
QuestionText, AnswerControl, AnswerDefaultText, IsItmandatory
Question1 TextBox null Yes
QuestionText2, RadioButton, Yes, Yes
Question3, ComboBox, null, no
..........................................
I need to get this data into object and conver the question text into TextBlock, and based on answercontrol value, need to create controls dynamically.
I tried like as you mentioned in your post, but data is not binding and not able to send default values as parameter values to converter.
My Converter is not getting called. Is there any thing wrong in below code?
My Codes are:
1)My Xaml Code:
<UserControl x:Class="SilverlightApplication5.DynamicControls"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SilverlightApplication5.Converter"
xmlns:question="clr-namespace:SilverlightApplication5"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White" Width="400" Height="400">
<Grid.Resources>
<local:UILocatorConverter x:Key="UILocatorConverter" />
<question:Questions x:Key="Questions"/>
</Grid.Resources>
<ListBox ItemsSource="{Binding Questions}" Width="400" Height="400">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<ContentControl Content="{Binding Converter={StaticResource UILocatorConverter},ConverterParameter={Binding QuestionText},Path=QuestionControl}" Grid.Column="0" />
<ContentControl Content="{Binding Converter={StaticResource UILocatorConverter},ConverterParameter={Binding DefaultValue},Path=AnswerControl}" Grid.Column="1" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
2) Code behind file code is:
namespace SilverlightApplication5
{
public partial class DynamicControls : UserControl
{
ObservableCollection<Questions> Question;
public DynamicControls()
{
InitializeComponent();
Question = new ObservableCollection<Questions>();
Question.Add(new Questions { QuestionControl = "TextBlock", QuestionText = "What is your name?", AnswerControl = "TextBox", AnswerValues = "", DefaultValue = "" });
Question.Add(new Questions { QuestionControl = "TextBlock", QuestionText = "What is your surname?", AnswerControl = "TextBox", AnswerValues = "", DefaultValue = "" });
Question.Add(new Questions { QuestionControl = "TextBlock", QuestionText = "Sex:", AnswerControl = "ComboBox", AnswerValues = "Male,Female,Others", DefaultValue = "Select a Value" });
Question.Add(new Questions { QuestionControl = "TextBlock", QuestionText = "Marital Status", AnswerControl = "RadioButton", AnswerValues = "", DefaultValue = "Not Married" });
this.DataContext = Question;
}
}
}
3) My converter is:
namespace SilverlightApplication5.Converter
{
public class UILocatorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
String param="This is control created dynamically";
if (parameter != null)
{
param = System.Convert.ToString(parameter);
}
switch (value.ToString())
{
case "TextBlock":
return new TextBlock() { Text = param, HorizontalAlignment=HorizontalAlignment.Center,TextWrapping=TextWrapping.NoWrap,Width=200 };
case "Button":
return new Button() { Content = param, Width=150 };
case "TextBox":
return new TextBox() { Text = param };
case "RadioButton":
return new TextBox() { };
case "ComboBox":
return new TextBox() { };
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
4) My Question Class is:
namespace SilverlightApplication5
{
public class Questions
{
private string _questionControl;
public string QuestionControl {
get
{
return _questionControl;
}
set
{
_questionControl = value;
}
}
private string _questionText;
public string QuestionText
{
get
{
return _questionText;
}
set
{
_questionText = value;
}
}
private string _answerControl;
public string AnswerControl
{
get
{
return _answerControl;
}
set
{
_answerControl = value;
}
}
private string _answerValues;
public string AnswerValues
{
get
{
return _answerValues;
}
set
{
_answerValues = value;
}
}
private string _defaultValue;
public string DefaultValue
{
get
{
return _defaultValue;
}
set
{
_defaultValue = value;
}
}
}
}
My converter is not getting called, is there any issues in this code?
You need to use this:
<ListBox ItemsSource="{Binding}" Width="400" Height="400">
As you want to access the collection of Questions you set in the DataContext.
What you were doing was creating a single Questions class in your Resources and telling the ListBox to use that.
So you won't need this at all:
<question:Questions x:Key="Questions"/>
(You might have to use BindsDirectlyToSource...because you are setting the DataContext to a collection directly...could be wrong on that!).
Alternatively, you can do this in your control:
public partial class DynamicControls : UserControl
{
public ObservableCollection<Questions> Question { get; set; }
...
Set the DataContext in this way:
DataContext = this;
And then use this Binding:
<ListBox ItemsSource="{Binding Question}" Width="400" Height="400">
I'd recommend you rename your Questions class to Question, and then rename the Property to Questions, to avoid confusion.