The resource is not present in the dictionary - c#

I'm trying to get a StaticResource at code behind but when I debug just get a empty response.
In my MainPage.xaml.cs I have:
public MainPage()
{
InitializeComponent();
/*Create buttons*/
for (int i = 0; i < 15; i++)
{
FlexGrid.Add(BtnAdd(i + 1));
}
}
private Button BtnAdd(int btnNum)
{
Button btn = new Button();
btn.Text = "TestButton " + btnNum;
btn.HorizontalOptions = LayoutOptions.Center;
btn.WidthRequest = 125;
btn.HeightRequest = 125;
//Here i get empty response
btn.BorderColor = Resources["Secondary"] as Color;
btn.BorderWidth = 5;
btn.Margin = new Thickness(5, 5, 5, 5);
btn.Clicked += TestBTN;
return btn;
}
When debug says:
System.Collections.Generic.KeyNotFoundException: 'The resource 'Secondary' is not present in the dictionary
The element is in the folder Resources/Styles/colors.xaml and is a ResourceDictionary in front i can take it just with {StaticResource Secondary}.
How can I get it at code behind?
EDIT
I find this question and I try the answers, the static class answer I don't know why I need a VisualElement and the others give me this:
var rd = App.Current.Resources.MergedDictionaries.First();
So now I take the Resource dictionary but with null response of each element.

a workaround is to make a local Resource which has a BasedOn property on the global style
<ContentPage.Resources>
<Style x:Key="button_icons_style_LOCAL" TargetType="Button" BasedOn="{x:StaticResource button_icons_style}"/>
</ContentPage.Resources>
and then to use the local one in the code.
new Button() { Style = (Style)Resources["button_icons_style_LOCAL"] }

Related

Binding without XAML [WPF]

I am designing an application with 256 buttons inside, and I am adding them in the WrapPanel in C# code using for loop. These buttons are not mentioned in XAML code.
My problem is that, when clicking on one of them, I have to change its color using binding.
I tried following code, but it does not work (only changes the content of the button):
private void NewButton_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
for (int i = 0; i < counter; i++)
{
if (btn.Name == ("Butt" + i))
{
btn.Content = "works";
MyData mydata = new MyData();
Binding binding = new Binding("Color");
binding.Source = mydata;
binding.Source = btn;
break;
}
}
}
and
private int counter = 0;
public class MyData
{
public static Brush _Color = Brushes.Red;
public Brush Color
{
get
{
return _Color;
}
}
}
public MainWindow()
{
InitializeComponent();
int num = number(3);
List<Button> btnList = new List<Button>();
for(int i =0; i<(num*num); i++)
{
Button button = new Button();
button.Name = "Butt" + counter;
button.Content = "New";
counter++;
button.Height = 35;
button.Width = 35;
button.Click += new RoutedEventHandler(NewButton_Click);
wp.Children.Add(button);
}
If what you are trying to do is bind the button's background color to your "MyData" class object, you are almost there...
First, create the binding object, set the source to your new instance of "mydata", and then the path to your "Color" property exposed.
THEN, you need to save the new BINDING object to your button control and tell it you want the BackgroundProperty bound to the newly created binding. The following minor adjustment to your code works. Not exactly why your approach is what it is for your overall project, but hopefully does what you intended.
if (btn.Name == ("Butt" + i))
{
btn.Content = "works";
MyData mydata = new MyData();
var oBind = new Binding
{
// bind its source to this view model instance
Source = mydata,
// what property on THE BUTTON do want to be bound to.
Path = new PropertyPath("Color")
};
btn.SetBinding(BackgroundProperty, oBind);
btn.DataContext = oBind;
break;
}

C# How to put RadioButton inside Panel

I have searched everywhere, but the procedure are so painful. How to put multiple RadioButton into a panel programatically without using toolbox. I'm using WinForms. After several suggestion/s, I still can't add the radiobuttons inside the panel.
public partial class Form1 : Form
{
RadioButton[] RadioButton_WallFirstStorey_Yes = new RadioButton[100];
RadioButton[] RadioButton_WallFirstStorey_No = new RadioButton[100];
Panel[] Panel_WallFirstStorey = new Panel[100];
int CheckBoxWidth = 100;
public Form1()
{
InitializeComponent();
//code
//procedure
}
private void InitializeRadioButton_Wall(RadioButton RadioButtonX)
{
RadioButtonX.AutoSize = true;
RadioButtonX.Font = SystemFonts.DefaultFont;
RadioButtonX.BackColor = Color.Transparent;
Controls.Add(RadioButtonX);
}
private void InitializePanel_Wall(Panel PanelX)
{
PanelX.BackColor = Color.PaleTurquoise;
PanelX.BorderStyle = BorderStyle.Fixed3D;
PanelX.BringToFront();
Controls.Add(PanelX);
}
private void MyProcedure()
{
int i;
for (i = 1; i <= 100; i++)
{
Panel_WallFirstStorey[i] = new Panel();
InitializePanel_Wall(Panel_WallFirstStorey[i]);
Panel_WallFirstStorey[i].Location = new Point(Label_SeparatorLineVertical[ColumnMinimum + i].Location.X, Label_SeparatorLineHorizontal[RowMinimum + i].Location.Y);
Panel_WallFirstStorey[i].Width = (Label_SeparatorLineVertical[ColumnMaximum].Location.X - Label_SeparatorLineVertical[ColumnMinimum].Location.X) / (ColumnMaximum - ColumnMinimum);
Panel_WallFirstStorey[i].Height = CheckBoxWidth;
Panel_WallFirstStorey[i].SendToBack();
}
for (i = 1; i <= 100; i++)
{
RadioButton_WallFirstStorey_Yes[i] = new RadioButton();
RadioButton_WallFirstStorey_No[i] = new RadioButton();
Panel_WallFirstStorey[i].Controls.Add(RadioButton_WallFirstStorey_Yes[i]);//I add this stuff
Panel_WallFirstStorey[i].Controls.Add(RadioButton_WallFirstStorey_No[i]);//I add this stuff
InitializeRadioButton_Wall(RadioButton_WallFirstStorey_Yes[i]);
InitializeRadioButton_Wall(RadioButton_WallFirstStorey_No[i]);
RadioButton_WallFirstStorey_Yes[i].Text = "Yes";
RadioButton_WallFirstStorey_No[i].Text = "No";
RadioButton_WallFirstStorey_Yes[i].Location = new Point(Panel_WallFirstStorey[i].Width / 3, 0);
RadioButton_WallFirstStorey_No[i].Location = new Point(Panel_WallFirstStorey[i].Width * 2 / 3, 0);
RadioButton_WallFirstStorey_Yes[i].Font = SystemFonts.DefaultFont;
RadioButton_WallFirstStorey_No[i].Font = SystemFonts.DefaultFont;
RadioButton_WallFirstStorey_Yes[i].BringToFront();
RadioButton_WallFirstStorey_No[i].BringToFront();
}
}
}
Wow, your code is wrong in so many ways.... It creates controls over and over whenever a panel is painted, but it never really adds them anywere.
To add a radio button b to a panel p, it would be enough to do this:
RadioButton b = new RadioButton();
// Set properties for button here (text, location, handlers, etc.)
p.Controls.Add(b);
I'd try the following procedure instead of yours:
private void MyProcedure()
{
for (i = 1; i <= 100; i++)
{
RadioButton_WallFirstStorey_Yes[i] = new RadioButton();
RadioButton_WallFirstStorey_No[i] = new RadioButton();
InitializeRadioButton_Wall(RadioButton_WallFirstStorey_Yes[i]);
InitializeRadioButton_Wall(RadioButton_WallFirstStorey_No[i]);
RadioButton_WallFirstStorey_Yes[i].Text = "Yes";
RadioButton_WallFirstStorey_No[i].Text = "No";
RadioButton_WallFirstStorey_Yes[i].Location = new Point(Panel_WallFirstStorey[i].Location.X + Panel_WallFirstStorey[i].Width / 3, Panel_WallFirstStorey[i].Location.Y);
RadioButton_WallFirstStorey_No[i].Location = new Point(Panel_WallFirstStorey[i].Location.X + Panel_WallFirstStorey[i].Width * 2 / 3, Panel_WallFirstStorey[i].Location.Y);
Panel_WallFirstStorey[i].Controls.Add(RadioButton_WallFirstStorey_Yes[i]);
Panel_WallFirstStorey[i].Controls.Add(RadioButton_WallFirstStorey_No[i]);
}
}
The following code indicates you're still doing it wrong, adding the radio buttons to the form itself, but positioning them as if you had added them to the panel:
RadioButton_WallFirstStorey_Yes[i].Location = new Point(Panel_WallFirstStorey[i].Location.X + Panel_WallFirstStorey[i].Width / 3, Panel_WallFirstStorey[i].Location.Y);
If you added the button to the panel, it would most probably be invisible because it is outside the panel. If you added the button to the panel, you'd have to use coordinates relative to the panel's client area.
RadioButton_WallFirstStorey_Yes[i].Location = new Point(Panel_WallFirstStorey[i].Width / 3, 0);
RadioButton_WallFirstStorey_No[i].Location = new Point(Panel_WallFirstStorey[i].Width * 2 / 3, 0);
Your update code shows clearly where your error is:
private void InitializeRadioButton_Wall(RadioButton RadioButtonX)
{
RadioButtonX.AutoSize = true;
RadioButtonX.Font = SystemFonts.DefaultFont;
RadioButtonX.BackColor = Color.Transparent;
// REMOVE THIS LINE!!
Controls.Add(RadioButtonX);
}
The last line adds the radio button to the form. As we've been telling you all the time. Remove the line I marked above. Then, the radio buttons will be added to the panels only. After that it is a question of getting the positions right.
You can for example create a panel (or a GroupBox) and in a loop add the RadioButtons.
It should work like with any other control in Winforms.
// Adds 10 Radiobuttons with the name "Radio <number>"
public Form1()
{
InitializeComponent();
for (int n = 0; n < 10; n++)
{
// First instantiate a new RadioButton.
RadioButton button = new RadioButton();
// Now the name of the button.
button.Text = "Radio" + n;
// Dock the button to the top of the GroupBox (to put them in order)
button.Dock = DockStyle.Top;
// Add the button to the GroupBox.
this.groupBoxRadio.Controls.Add(button);
}
}
Your question is not very clear, and no code for context, but you should be able to create an instance of a new radiobutton and add it to the controls of the panel.
It may also be best to use RadioButtonList like Harvey has mentioned, but to try to answer your question:
var someRadioBtn = new RadioButton();
// set properties...
pnlMyPanel.Controls.Add(someRadioBtn);

How to get button name added on UniformGrid runtime?

Get Button name added on UniformGrid during run time.
My code is:
for (int i = 1; i <= no; ++i)
{
Button button = new Button()
{
Content = i,
Tag = i,
Background = Brushes.White,
Height = 30,
Width = 30,
Name="A" + i.ToString()
};
string name=button.Name;
button.Click += new RoutedEventHandler(button_Click);
this.grid1.Children.Add(button);
if (name.Equals("A1"))
{
button.Background = Brushes.White;
}
}
My requirement is to get Button name in other function:
private void Sum()
{
}
Here is my XAML:
<UniformGrid x:Name="grid1" Margin="816,115,96,354" Grid.Column="1" />
It isn't clear what is the ultimate goal here. But you can loop through all child of UniformGrid which type is Button to get name of each button and take action accordingly :
foreach (var btn in grid.Children.OfType<Button>())
{
var btnName = btn.Name;
//take action according to button name
}

How Do I bind a button Content with a list of numbers in WP8?

At first let me tell you, what I want to achieve. I want that when a windows page loads it will create a lot of buttons, say 10 buttons now at run time I want this Button.Content to Bind with some listvalues, which is a list of 10 numbers.
public List<int> listvalues = new list<int>();
I want to do this in MVVM, so my approach is in model I have public int ListNumbers property, with OnPropertyChanged event is defined. Now in the view Model, how do I fill a list listvalues with some 10 integer values(Exactly new to MVVM that's why I am asking). This Ten values will be used for the Content of the 10 Buttons that are run time generated. And after filling the listvaluesin the MainPage_Loaded Method of the MainPage how do bind the Content of the Button with the listvalues .
To better understand my requirement...
I have below XAMl code
<Canvas x:Name="GameCanvas" Background="Bisque" Height="480" Width="480" /> in MainPage.xaml
So in the code behind
int locationFirst = 25;
int locationSecond = 100;
char SeatValue = 'A';
int row = 3;
int column = 3;
public GamePage()
{
InitializeComponent();
for (int x = 1; x <= row; x++)
{
for (int i = 1; i <= column; i++)
{
CreateButtons(SeatValue.ToString() + i, locationFirst, locationSecond);
locationFirst = locationFirst + 130;
}
locationFirst = 25;
locationSecond = locationSecond + 50;
}
}
The createButtons code is
Button btnNew = new Button();
btnNew.Name = btnName;
btnNew.Margin = new Thickness(btnPointFirst, btnPointSecond, 0, 0);
btnNew.Width = 100;
btnNew.Height = 70;
GameCanvas.Children.Add(btnNew);
In the Windows Phone I found an issue, is that there is no btnNew.Location(X,Y);
So at run time I have to use
btnNew.Margin = new Thickness(btnPointFirst, btnPointSecond, 0, 0);
which is not putting the buttons in the desired location. However this is my code now how do I assign btnNew.Content with the listNumbers value?
Please help.
Any link or any elaborate answer is fine for me...
Thanks
I hope I understood this one
public GamePage()
{
InitializeComponent();
this.DataContext = GamePageViewModel();
for (int x = 1; x <= row; x++)
{
for (int i = 1; i <= column; i++)
{
CreateButtons(SeatValue.ToString() + i, locationFirst, locationSecond);
locationFirst = locationFirst + 130;
}
locationFirst = 25;
locationSecond = locationSecond + 50;
}
}
public class GamePageViewModel
{
//List of numbers to put e.g. List<int>
//Change PropertyNameOfTheViewModel here to properties, say 10 properties e.g, public int Content { get; set; }
}
Button btnNew = new Button();
btnNew.Name = btnName;
btnNew.Margin = new Thickness(btnPointFirst, btnPointSecond, 0, 0);
btnNew.Width = 100;
btnNew.Height = 70;
btnNew.SetBinding(Button.ContentProperty,new Binding("PropertyNameOfTheViewModel");
But then, I wouldn't recommend doing this kind of stuff in the ViewModel because it is unnecessary, you only use the binding to a ViewModel if the one you are planning to show in the UI is coming from a database/business logic. Setting button contents from 1-10 is not gonna be in the ViewModel, if you continue you'll end up with unnecessary code in the ViewModel thus breaking the MVVM pattern.
My question is, why do you have to do this with binding? Just set the Button Content when you are creating it in the MainPage.xaml.cs, that is correct. You are just adding unnecessary layer just to set the button's content.

WPF: Dynamical Label addition in Grid

I have to create a table to display the KEY VALUE kind of thing.
I tried the below code but messed up with overlapping output. I believe, I need to create the Grid RowDefinitions and ColumnDefinitions but not able to achieve it. Please help me.
XAML:
<Window x:Class="GrideLabel.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Name="LabelGrid"></Grid>
</Window>
Code behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
AddLabelDynamically();
}
private void AddLabelDynamically()
{
for (int i = 0; i < 3; i++)
{
Label nameLabel = new Label(); nameLabel.Content = "KEY :"+i.ToString();
Label dataLabel = new Label(); dataLabel.Content = "VALUE :"+i.ToString();
//I want to creatre the Seperate coloum and row to display KEY
// VALUE Pair distinctly
this.LabelGrid.Children.Add(nameLabel);
this.LabelGrid.Children.Add(dataLabel);
}
}
}
You have to define Row and Column definitions and assign Rows and Columns to child Controls. Following code does that:
private void AddLabelDynamically()
{
this.LabelGrid.ColumnDefinitions.Clear();
this.LabelGrid.RowDefinitions.Clear();
this.LabelGrid.ColumnDefinitions.Add(new ColumnDefinition());
this.LabelGrid.ColumnDefinitions.Add(new ColumnDefinition());
for (int i = 0; i < 3; i++)
{
this.LabelGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
Label nameLabel = new Label(); nameLabel.Content = "KEY :" + i.ToString();
Label dataLabel = new Label(); dataLabel.Content = "VALUE :" + i.ToString();
Grid.SetRow(nameLabel, i);
Grid.SetRow(dataLabel, i);
Grid.SetColumn(nameLabel, 0);
Grid.SetColumn(dataLabel, 1);
//I want to creatre the Seperate coloum and row to display KEY
// VALUE Pair distinctly
this.LabelGrid.Children.Add(nameLabel);
this.LabelGrid.Children.Add(dataLabel);
}
}

Categories