UWP: Updating a Background in an ItemTemplate based on a condition - c#

In a UWP project a ListView is bound to a collection player objects. Each player object has a property such as HighScore. The ItemTemplate of the ListView shows the HighScorefor each player. I want to change the Background of the Grid in the ItemTemplate that shows the HighScore when it's HighScore matches the BiggestScore (a property of the Page's DataContext). This represents the largest score across all players. BiggestScore is updated after the HighScore is set.
Any ideas how I can achieve this?
Here is some example code which hopefully illustrates the various pieces.
XAML:
<Grid x:Name="root" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView x:Name="lvwPlayers" ItemsSource="{Binding Players}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid x:Name="grdHighScore" Background="Yellow">
<TextBlock Text="{Binding HighScore}"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
CODE BEHIND:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
var allPlayers = new AllPlayers();
allPlayers.Players.Add(new Player(100));
allPlayers.Players.Add(new Player(112));
allPlayers.Players.Add(new Player(1160));
allPlayers.Players.Add(new Player(122));
this.DataContext = allPlayers;
}
}
PLAYER:
public class Player : INotifyPropertyChanged
{
protected void OnPropertyChanged([CallerMemberName] string caller = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(caller));
}
public event PropertyChangedEventHandler PropertyChanged;
public Player( int high)
{
HighScore = high;
}
private int _highScore;
public int HighScore
{
get { return _highScore; }
set
{
_highScore = value;
OnPropertyChanged();
}
}
}
ALLPLAYERS:
public class AllPlayers : INotifyPropertyChanged
{
public ObservableCollection<Player> Players { get; set; }
public AllPlayers()
{
Players = new ObservableCollection<Player>();
}
protected void OnPropertyChanged([CallerMemberName] string caller = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(caller));
}
public event PropertyChangedEventHandler PropertyChanged;
public void ChangeScore(int playerIndex, int highScore)
{
Players[playerIndex].HighScore = highScore;
}
private void UpdateBiggestScore()
{
BiggestScore = (from player in Players select player.HighScore).Max();
}
private int _biggestScore;
public int BiggestScore
{
get { return _biggestScore; }
set
{
_biggestScore = value;
OnPropertyChanged();
}
}
}

Create property in your DataContext saying whether HighScore is bigger than BiggestScore, eg. bool IsBiggest
Bind it:
Background={Binding IsBiggest, Converter=HighScoreToColorConverter}
where YourConverter may be something like:
public class HighScoreToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var isBiggest = (bool)value;
var color = isBiggest ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Yellow);
return color;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
var color = value as SolidColorBrush;
if (color != null)
{
return color == new SolidColorBrush(Colors.Red);
}
return false;
}
}

You could add the Background Color as a Property to your Player
private SolidColorBrush _backgroundColor = new SolidColorBrush(Colors.Yellow);
public SolidColorBrush BackgroundColor
{
get { return _backgroundColor; }
set
{
_backgroundColor= value;
OnPropertyChanged();
}
}
and bind it to the Background of the Grid
<Grid x:Name="grdHighScore" Background="{Binding BackgroundColor}">
<TextBlock Text="{Binding HighScore}"/>
</Grid>
When you update the Biggest Score, get the player Object with the biggest score and update the Background. Also change the background of all other players back to Yellow.

Related

ListView not displaying until I swipe the screen

I trying to implement StateContainer by Patrick McCurley in my .NET MAUI application.
It works correctly when the ListView displayed for the first time.
But ListView is not displaying when state changes again until I swipe the screen.
When I add any view element (label, button, etc.) to the view that contains the ListView, it does not show up. But ListView displayed correctly when I move StateContainer to Grid with any other view elements. ListView does not display correctly if the Grid contains no other elements than the StateContainer.
I can't figure out what's the problem here. Grid with other view elements is not a solution for me, because my page should not contain any other elements whan the StateContainer.
Here is an example that reproduces the problem:
P.S. I'm sorry for a lot of code :) I don't know where the problem could be.
States.cs
public enum States
{
Loading,
Success
}
StateCondition.cs
[ContentProperty("Content")]
public class StateCondition : View
{
public object State { get; set; }
public View Content { get; set; }
}
StateContainer.cs
[ContentProperty("Conditions")]
public class StateContainer : ContentView
{
public List<StateCondition> Conditions { get; set; } = new();
public static readonly BindableProperty StateProperty =
BindableProperty.Create(nameof(State), typeof(object), typeof(StateContainer), null, BindingMode.Default, null, StateChanged);
private static void StateChanged(BindableObject bindable, object oldValue, object newValue)
{
var parent = bindable as StateContainer;
if (parent != null)
parent.ChooseStateProperty(newValue);
}
public object State
{
get { return GetValue(StateProperty); }
set { SetValue(StateProperty, value); }
}
private void ChooseStateProperty(object newValue)
{
if (Conditions == null && Conditions?.Count == 0) return;
var stateCondition = Conditions
.FirstOrDefault(condition =>
condition.State != null &&
condition.State.ToString().Equals(newValue.ToString()));
if (stateCondition == null) return;
Content = stateCondition.Content;
}
}
MainPage.xaml
<ContentPage ...>
<state:StateContainer State="{Binding State}">
<state:StateCondition State="Loading">
<StackLayout HorizontalOptions="Center" VerticalOptions="Center">
<ActivityIndicator IsRunning="True" />
<Label Text="Updating data..." />
</StackLayout>
</state:StateCondition>
<state:StateCondition State="Success">
<ListView ItemsSource="{Binding SomeData}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding . }" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</state:StateCondition>
</state:StateContainer>
</ContentPage>
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
private States _state;
private int[] _someData;
public MainPage()
{
InitializeComponent();
this.BindingContext = this;
SomeData = new[] { 1, 2, 3, 4, 5 };
State = States.Success;
// it can be executed from outside the page
_ = Task.Run(ExecuteSomeWorkAsync);
}
public States State
{
get => _state;
private set
{
if (_state != value)
{
_state = value;
OnPropertyChanged();
}
}
}
public int[] SomeData
{
get => _someData;
private set
{
if (_someData != value)
{
_someData = value;
OnPropertyChanged();
}
}
}
public async Task ExecuteSomeWorkAsync()
{
await Task.Delay(2000);
State = States.Loading;
await Task.Delay(2000);
// generate new data for displaying
Random rnd = new();
var data = Enumerable.Range(0, 5).Select(n => rnd.Next(0, 5)).ToArray();
SomeData = data;
State = States.Success;
}
}
I suspect Content = stateCondition.Content; won't update display correctly.
As an alternative solution, define public class StateContainer : StackLayout, and use IsVisible="True"/"False" on each child, to control what is shown. All the stateConditions continue to be children of stateContainer, but make only one visible at a time.

How to reflect changes made in CarouselView.ItemsSource in the carouselView? (Xamarin Forms)

I was working on my Xamarin.Forms app, trying to make the Items inside my scrollview change their TransitionX property when scrolling, the problem is that once the scrollview has been shown the items inside it will not change as the source does unless you reassign the carouselview.ItemSource, but I can't do this because it would be extremely inefficient and the scrolling would be awful.
So is there any way to reflect the changes made in the source, in the carouselView dynamically?
Here goes my code, I have written comments to make it as clear as possible:
CarouselView:
<MasterDetailPage.Detail>
<ContentPage Title="title">
<StackLayout
x:Name="page">
<CarouselView
x:Name="carousel"
VerticalOptions="StartAndExpand"
HorizontalOptions="StartAndExpand"
BackgroundColor="Transparent"
Scrolled="carousel_Scrolled">
<CarouselView.Behaviors>
<behaviors:CarouselViewParallaxBehavior ParallaxOffset="100"/>
</CarouselView.Behaviors>
<CarouselView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid>
//Here goes more content which is irrelevant for this matter
</Grid>
<Image
Source="{Binding ImageSrc}"
BackgroundColor="Transparent"
HeightRequest="500"
//This is the property I am trying to change when scrolling
TranslationX="{Binding Position}"
VerticalOptions="Center"
HorizontalOptions="Center"
Margin="0,-160,0,0"></Image>
</Grid>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
</StackLayout>
</ContentPage>
</MasterDetailPage.Detail>
My xaml.cs code:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HomePage : MasterDetailPage
{
private List<Color> _backgroundColorscount = new List<Color>();
private List<Color> _backgroundColors = new List<Color>();
private List<Product> Items;
private static double position = 0;
public HomePage()
{
InitializeComponent();
//These are the items of my carouselView
Items = new List<Product>()
{
// Just create some dummy data here for now.
new Product{Title = "Classic burguer", Price = "124$", ImageSrc = "Burguer.png", StartColor = Color.FromHex("#DF8000"), EndColor = Color.FromHex("#DCD800")},
new Product{Title = "Classic burguer", Price = "124$", ImageSrc = "Burguer.png", StartColor = Color.FromHex("#15DE00"), EndColor = Color.FromHex("#BADE00")},
new Product{Title = "Classic burguer", Price = "124$", ImageSrc = "Burguer.png", StartColor = Color.FromHex("#00DEAD"), EndColor = Color.FromHex("#DCD800")}
};
carousel.ItemsSource = Items;
}
private void carousel_Scrolled(object sender, ItemsViewScrolledEventArgs e)
{
//Here is what I am trying to do (I wrote it right now to show the problem)
Items[0].Position = position - 10;
// the position property in Items[0] is changed, but the change is not reflected in the carouselView
}
}
My Model class:
class Product
{
#region Bindings
//Item views
public string Title { get; set; }
public string Price { get; set; }
public string ImageSrc { get; set; }
public string Description { get; set; }
// Gradient colors
private Color startColor;
public Color StartColor
{
get
{
return startColor;
}
set
{
startColor = value;
}
}
private Color endColor;
public Color EndColor
{
get
{
return endColor;
}
set
{
endColor = value;
}
}
private Color backgroundColor;
public Color BackgroundColor
{
get
{
if (startColor != null && endColor != null)
backgroundColor = GetBackGroundColor();
return backgroundColor;
}
}
//Item Properties
private double _position;
public double Position
{
get
{
return _position;
}
set
{
_position = value;
OnPropertyChanged();
}
}
private double _scale;
public double Scale
{
get { return _scale; }
set
{
_scale = value;
OnPropertyChanged();
}
}
#endregion
public Product()
{
Scale = 1;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
And that is all, if you need more code or info I will provide it to you as soon as I see your request. Thank you all for your time, have a good day.
Well use bindings to make our life easier:
In your XAML:
<ListView ItemsSource="{Binding Items}" ...../>
In your C# side Items will be an observable collection
public ObservableCollection<Product> Items { get; set; }
Also, you won't need
carousel.ItemsSource = Items;
Rest would stay the same now as soon as you make any changes to the collection the carousel should change too.
Note: All properties of the Product class would need to notify on property changed.

Binding Background Color of style from a class

in my app i have ColorToBrushConverter.cs, ColorItem.cs and a box page which contain some collection of colors when user click on any of color and back to mainpage it save to settings isolated storage then i able to set my stackpanel any any element background to choosed color from that colorbox page.
But Problem is i have a style in which i want color binding so can we do it from c# or use color binding in xaml from below class.
ColorToBrushConverter.cs
namespace CustomColorsPicker.Converters
{
public class ColorToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
return new SolidColorBrush((Color)(value));
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
ColorItem.cs
namespace ColorBox
{
public class ColorItem
{
public Color Color { get; set; }
}
}
BoxPage.Xaml
contains list of color
xmlns:converters="clr-namespace:CustomColorsPicker.Converters"
<Page.Resources>
<converters:ColorToBrushConverter x:Key="ColorToBrushConverter"/>
</Page.Resources>
//////////
<ListBox Grid.Row="2" Name="listBox" ScrollViewer.VerticalScrollBarVisibility="Disabled" SelectionChanged="lstColor_SelectionChanged" Width="460" Height="770" Margin="0,20,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="item" Orientation="Horizontal" Margin="10,10,0,0">
<Border CornerRadius="5" BorderThickness="2" BorderBrush="{Binding Color, Converter={StaticResource ColorToBrushConverter}}">
<Rectangle Fill="{Binding Color, Converter={StaticResource ColorToBrushConverter}}" Width="50" Height="50" />
</Border>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
BoxPage.xaml.cs
//Constructor. list of colors
static uint[] uintColors =
{
0xFFD9325D,
0xFFFFFF00,0xFFFFE135,0xFFFFFF66,0xFFF8DE7E,0xFF008000,0xFF008A00
};
public BoxPage()
{
InitializeComponent();
this.Loaded += BoxPage_Loaded;
}
private async void BoxPage_Loaded(object sender, RoutedEventArgs e)
{
List<ColorItem> item = new List<ColorItem>();
for (int i = 0; i < 67; i++)
{
item.Add(new ColorItem() { Color = ConvertColor(uintColors[i])});
};
listBox.ItemsSource = item;
}
private void lstColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
(Application.Current as App).CurrentColorItem = ((ColorItem)e.AddedItems[0]);
}
}
MainPage.xaml.cs
//Constructor
IsolatedStorageSettings ColourSettings = IsolatedStorageSettings.ApplicationSettings;
public MainPage()
{
InitializeComponent();
InitializeSettings();
}
private void InitializeSettings()
{
if (!ColourSettings.Contains("LastColorItem"))
{
ColorItem item = new ColorItem();
item.Color = Colors.Cyan;
ColourSettings.Add("LastColorItem", item);
}
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
ColourSettings["LastColorItem"] = _colorItem;
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (ColourSettings.Contains("LastColorItem"))
{
_colorItem = (ColorItem)ColourSettings["LastColorItem"];
}
ColorItem myColorItem = (Application.Current as App).CurrentColorItem;
if (myColorItem != null)
{
_colorItem = (ColorItem)myColorItem;
}
MyFillStackPanel.Background = new SolidColorBrush(_colorItem.Color);
MyCtrlPanelBorder.Background = new SolidColorBrush(_colorItem.Color);
}
MainPage.xaml
xmlns:converters="clr-namespace:CustomColorsPicker.Converters"
<Page.Resources>
<converters:ColorToBrushConverter x:Key="ColorToBrushConverter"/>
</Page.Resources>
In One of my style i want to bind it with above color because i am unable to do or edit style in c#
//SomeStyle
<DiscreteObjectKeyFrame.Value>
<SolidColorBrush Color="{**i want to bind color here**}"/>
</DiscreteObjectKeyFrame.Value>
Assuming your converter is working correctly, what is actually missing in your code is the actual Binding process.
Your ColorItem class (which needs to derive from the interface INotifyPropertyChanged) has to declare the PropertyChanged event.
When your property Color gets modify you want to raise an event, so the UI gets notified that the property Color has been updated.
You do that on convention by calling a method with the same name as your eventhandler prefixed by "On", therefore you would have to implement the method
OnPropertyChanged, which as I've mentioned would be responsible for actually raising the PropertyChanged event.
There are many ways from which you can define this implementation, but you can look here to see an implementation from Microsoft themselves.
enter link description here
Expose your property,
public ColorItem MyColor {get;set;}
so when you define your {Binding ...} the CLR will be able to find the property during Runtime.
In the MainPage constructor, you can initialize this property
MyColor = new ColorItem();
And define the DataContext of the page as:
this.DataContext = MyColor;
Now you should be able to have your source update the target with the code which you have defined. If you intend to have your UI to propagate modifications onto the source you have to define the Binding with Mode=TwoWay, since the default mode for Binding is Mode=OneWay
Edit
public class ColorItem: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public Color color
{
get
{
return _color;
}
set
{
_color = value;
this.OnPropertyChanged();
}
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
// Raise the PropertyChanged event, passing the name of the property whose value has changed.
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Expose the property and set it as the DataContext of your page.
Then reference it in the Binding by {Binding MyColor.color .... }

Trouble binding XAML uwp

Hi I am following this tutorial,http://blogs.u2u.be/diederik/post/2011/11/14/null.aspx, to bind the visibility of an element to a Boolean property. The program is not working. Here is the code:
<Page.Resources>
<local:BooleanToVisibilityConverter x:Key="TrueToVisibleConverter"/>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<TextBlock Text=" Hello World"
Visibility="{Binding Path=Show_element, Converter={StaticResource TrueToVisibleConverter}}"/>
<Button Click="Button_Click">press button</Button>
</StackPanel>
</Grid>
public sealed partial class MainPage : Page , INotifyPropertyChanged
{
private bool show_element ;
public bool Show_element
{
get { return show_element; }
set
{
show_element = value;
this.OnPropertyChanged();
Debug.WriteLine("Show_element value changed");
}
}
public MainPage()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Show_element = !Show_element;
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public void OnPropertyChanged(string propertyName = null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class BooleanToVisibilityConverter : IValueConverter
{
public bool IsReversed { get; set; }
public object Convert(object value, Type typeName, object parameter, string language)
{
var val = System.Convert.ToBoolean(value);
if (this.IsReversed)
{
val = !val;
}
if (val)
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
The visibility does not change with the property. I was having an error due to intellisense (Error Xaml namespace) which was resolved. Not sure what is wrong with this code.
Thank you.
change
this.OnPropertyChanged();
to
this.OnPropertyChanged("Show_element");
edit:
besides that, you don't have a ViewModel (sorry, missed that when I was checking your code), so you need to create one and set it as DataContext:
ViewModel.cs:
public class ViewModel : INotifyPropertyChanged
{
private bool show_element;
public bool Show_element
{
get { return show_element; }
set
{
show_element = value;
this.OnPropertyChanged("Show_element");
Debug.WriteLine("Show_element value changed");
}
}
public ViewModel()
{
}
public void ButtonClicked()
{
Show_element = !Show_element;
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public void OnPropertyChanged(string propertyName = null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
and your MainPage.xaml.cs should look somehow like that:
public sealed partial class MainPage : Page
{
private ViewModel _viewModel;
public MainPage()
{
this.InitializeComponent();
_viewModel = new ViewModel();
DataContext = _viewModel;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
_viewModel.ButtonClicked();
}
}

C# Binding List to ComboBox

I have a problem with my binding. Everything works except that the initial value displayed in the combo box of the selected is blank. The drop down has the two values below the blank that is originally display. Any help would be fantastic.
Main Class
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
public Data myData = new Data(new LocationSite("There", 9.81234));
Binding b = new Binding();
b.Source = MainWindow.Data.Location;
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
b.Path = new PropertyPath("Gravity");
MainWindow.mainWindow.Gravity.SetBinding(TextBox.TextProperty, b);
Binding b = new Binding() { Source = MainWindow.Data.LocationSelection };
MainWindow.mainWindow.LocationComboBox.DisplayMemberPath = "Name";
MainWindow.mainWindow.LocationComboBox.SetBinding(ComboBox.ItemsSourceProperty, b);
//bind selection
MainWindow.mainWindow.LocationComboBox.DataContext = MainWindow.Data;
Binding selectedItemBinding = new Binding() { Source = MainWindow.Data, Path = new PropertyPath("Location"), Mode = BindingMode.TwoWay}
MainWindow.mainWindow.LocationComboBox.SetBinding(ComboBox.SelectedValueProperty, selectedItemBinding);
MainWindow.mainWindow.LocationComboBox.SelectedIndex = 0; // always index 0 but might need index 1 how do I make it use whatever location is?
}
}
Data class with a list of Locations and one location that is the selected. Somehow I need to tell the combo box that the one to select is the location that matched the list. Any Help????
public class Data : INotifyPropertyChanged
{
private LocationSite location;
private List<LocationSite> locationSelection;
public Location(LocationSite useLocation)
{
location = useLocation; // can either be "Here" or "There" need start index either 0 or 1
locationSelection = new List<LocationSite>();
locationSelection.Add(new LocationSite("Here", 9.795884));
locationSelection.Add(new LocationSite("There", 9.81234));
}
public LocationSite Location
{
get { return location; }
set {
if (location == null)
{
location = new LocationSite();
}
Location.Gravity = value.Gravity;
Location.Name = value.Name;
}
}
/// <summary>
/// Getter/Setter of a list of LocationSites
/// </summary>
public List<LocationSite> LocationSelection
{
get { return locationSelection; }
set { locationSelection = value; }
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(
this, new PropertyChangedEventArgs(propName));
}
}
The object that I have a list of
public class LocationSite : INotifyPropertyChanged
{
private string name;
private double gravity;
public LocationSite(string siteName, double siteGravity)
{
Name = siteName;
Gravity = siteGravity;
}
public string Name
{
get { return name; }
set { name = value;
this.OnPropertyChanged("Name");
}
}
public double Gravity
{
get { return gravity; }
set { gravity = value;
this.OnPropertyChanged("Gravity");
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(
this, new PropertyChangedEventArgs(propName));
}
}
}
The XAML file
<Window x:Class="Data.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Needs to be updated" Height="820" Width="1280" HorizontalAlignment="Left">
<Grid Name="MainScreenGrid">
<TextBox x:Name="Gravity" Grid.Column="8" HorizontalAlignment="Left" Height="23" Grid.Row="3" TextWrapping="NoWrap" Text="0.0" VerticalAlignment="Top" Width="140" IsHitTestVisible="False" IsReadOnly="True"/>
<ComboBox x:Name="LocationComboBox" Grid.Column="6" HorizontalAlignment="Left" Grid.Row="1" VerticalAlignment="Top" Width="140" Height="22"/>
</Grid>
</Window>
in your constructor try this
LocationComboBox.SelectedIndex = 0;
In your Data Class Try this
private LocationSite location;
public LocationSite Location
{
get
{
return location;
}
set
{
location=value;
OnPropertyChanged("Location")
}
}
And in MainWindowConstructor Set the Value Like This
MainWindow.Data.Location=MainWindow.Data.LocationSelection.FirstOrDefault();
In this method By default It will Take the First Item of LocationSelection as Location.
And You need to Use System.Linq NameSpace for FirstOrDefault().
Set the Location Value Before You Set the Binding.

Categories