How to set icon of a button in ViewModel? - xamarin.forms

I have an icon button and i need to change the icon once user presses the button. I used to change it in the content page before, now if i dont set the value at the top there is no icon what so ever and if i set it in my load method the picture wont check, but if i set it the the top i cant change it either.
private string _playPauseButton = IconsFont.Volume2;
public string PlayPauseButton
{
get { return _playPauseButton; }
set
{
_playPauseButton = value;
NotifyPropertyChanged(nameof(_playPauseButton));
}
}
public ViewModel()
: base(listenCultureChanges: true)
{
Task.Run(async () => await LoadAllDataForDictionary()).Wait();
PlayPauseCommand = new Command(() => StartOrStopPlaying());
}
private void StartOrStopPlaying()
{
if (!viewDisabled)
{
var paused = LangUpDictionaryPlayer.PlayPause();
if (paused)
{
LangUpDictionaryPlayer.SetTrack(_word.Id);
_playPauseButton = IconsFont.AudioPause;
}
else
{
_playPauseButton = IconsFont.Volume2;
}
}
}
Also
what difference would i make by doing this
public string PlayPauseButton
{
set
{
_playPauseButton = value;
NotifyPropertyChanged();
}
get => _playPauseButton;
}
INsted of what i have?

Solved it by using the Public in the code
PlayPauseButton = IconsFont.AudioPause;

Related

How can i press a button in headerbar and do things in window in vala

How to make a button in headerbar and do things in window i've tried:
public class headerbar : Gtk.HeaderBar {
construct {
title = "Quiz";
subtitle = "You can solve this!";
show_close_button = true;
Gtk.Button button = new Gtk.Button.with_label ("Quit");
button.get_style_context ().add_class ("suggested-action");
button.set_valign (Gtk.Align.CENTER);
button.clicked.connect (() => {
var label = new Gtk.Label ("Hi");
main.add (label);
label.show ();
});
pack_start (button);
}
}
I got a sample as follow, hope it could help you:
public class AppTitleBar : Gtk.HeaderBar {
private Gtk.Button m_new_tab_button;
private Gtk.Box m_app_title_gui_box;
private Gtk.MenuButton m_main_menu_button;
public weak Workbench workbench { get; construct; }
public AppTitleBar (Workbench workbench) {
Object ( workbench: workbench );
}
construct {
set_show_close_button (true);
this.build_title_bar_layout();
}
public void add_new_tab(Widget title_widget)
{
m_app_title_gui_box.pack_start(title_widget);
title_widget.focus.connect(() => {
this.update_tab_inactive_all();
return true;
});
}
public void update_tab_inactive_all()
{
m_app_title_gui_box.foreach ((widget) => {
widget.set_opacity(0.3);
});
}
public void remove_tab_widget(Widget tab_bar)
{
m_app_title_gui_box.remove(tab_bar);
}
private void build_title_bar_layout()
{
m_main_menu_button = new Gtk.MenuButton ();
var menu_image = new Gtk.Image.from_icon_name ("open-menu-symbolic", Gtk.IconSize.BUTTON);
m_main_menu_button.set_image (menu_image);
m_main_menu_button.tooltip_text = ("Main Menu");
// create title bar box
m_app_title_gui_box = new Box(Orientation.HORIZONTAL, 2);
// create add new tab button
m_new_tab_button = new Gtk.Button.from_icon_name("list-add", Gtk.IconSize.BUTTON);
m_new_tab_button.get_style_context ().add_class ("back-button");
m_new_tab_button.valign = Gtk.Align.CENTER;
m_new_tab_button.always_show_image = true;
m_new_tab_button.can_focus = false;
m_new_tab_button.action_name = WorkbenchActions.ACTION_PREFIX + WorkbenchActions.ACTION_TAB_NEW;
m_new_tab_button.has_tooltip = true;
m_new_tab_button.tooltip_text = "Open a new connection (Ctrl+N)";
this.pack_end(m_main_menu_button);
this.pack_start(m_app_title_gui_box);
this.pack_start(m_new_tab_button);
}
}

Enable Always on Top For Caliburn Managed Window

I have the following ViewModel and I am using Caliburn Micro. The IWindowManager instance is properly resolved and all of the code works. As indicated by the TODO comment, I need to get a reference to the current window so I can toggle the AlwaysOnTop attribute. How can I do that?
namespace CaliburnWizardPlay
{
[Export(typeof(DropWindowViewModel))]
public class DropWindowViewModel : PropertyChangedBase, IHaveDisplayName
{
private readonly IWindowManager windowManager;
[ImportingConstructor]
public DropWindowViewModel(IWindowManager windowManager)
{
this.windowManager = windowManager;
}
public string DisplayName
{
get { return "Main Window"; }
set { }
}
public bool AlwaysOnTop
{
get { return Settings.Default.DropWindowAlwaysOnTop; }
set
{
Settings.Default.DropWindowAlwaysOnTop = value;
Settings.Default.Save();
NotifyOfPropertyChange(() => AlwaysOnTop);
//todo: toggle the AOT attribute of the window
}
}
public void FileDropped(DragEventArgs eventArgs)
{
if (eventArgs.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] droppedFilePaths = eventArgs.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string path in droppedFilePaths)
{
MessageBox.Show(path);
}
windowManager.ShowWindow(new WizardViewModel());
}
}
}
}
You can use the settings parameter of the ShowWindow method to set any property (e.g. Topmost) on the created window with a dictionary containing propertyname-value pairs:
windowManager.ShowWindow(new WizardViewModel(),
settings: new Dictionary<string,object> { {"Topmost", AlwaysOnTop} });
If you want to change the Topmost property of the already created window I see three options (in the order of preference):
Create an AlwaysOnTop property on the WizardViewModel and store the viewmodel in a private field and delegate the AlwaysOnTop to the WizardViewModel:
private WizardViewModel wizardViewModel;
public void FileDropped(DragEventArgs eventArgs)
{
//...
wizardViewModel = new WizardViewModel()
windowManager.ShowWindow(wizardViewModel);
}
public bool AlwaysOnTop
{
get { return Settings.Default.DropWindowAlwaysOnTop; }
set
{
//...
if (wizardViewModel != null)
wizardViewModel.AlwaysOnTop = value;
}
}
And in your view you can bind the WizardViewModel's AlwaysOnTop property to the window's TopMost property.
You can use the Application.Windows to retrieve the window. E.g. set the Name property of the created Window with the settings dictionary and then:
windowManager.ShowWindow(new WizardViewModel(),
settings: new Dictionary<string,object>
{ {"Topmost", AlwaysOnTop}, {"Name", "WizardWindow"} });
public bool AlwaysOnTop
{
get { return Settings.Default.DropWindowAlwaysOnTop; }
set
{
//...
var wizardViewModel = Application.Current.Windows.OfType<Window>()
.SingleOrDefault(w => w.Name == "WizardWindow");
if (wizardViewModel != null)
wizardViewModel.AlwaysOnTop = value;
}
}
Derive from the WindowManager and register it in your Bootstrapper and then you can override the CreateWindow, EnsureWindow etc. methods to store the created windows somewhere set the additional properties etc.

User Control's child controls not getting instantiated

public partial class ChatUserControl : System.Web.UI.UserControl
{
UserChatClass ucc = new UserChatClass();
public ChatUserControl()
{
lblChatFriend = new Label();
txtChatMessage = new TextBox();
imgFriend = new Image();
rpChatMessages = new Repeater();
}
public string ChatFriend { get { return this.lblChatFriend.Text; } set { this.lblChatFriend.Text = value; } }
public string imgFriendUrl { get { return this.imgFriend.ImageUrl; } set { this.imgFriend.ImageUrl = value; } }
public object rpChatDataSource { get { return this.rpChatMessages.DataSource; } set { this.rpChatMessages.DataSource = value; } }
public Repeater rpChatMessagesToBind { get { return this.rpChatMessages; } set { this.rpChatMessages = value; } }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ChatUserControl user1 = new ChatUserControl();
divChatUserControlCover.Controls.Add(user1);
}
}
private void BindUserControls()
{ ChatUserControl user1 = divChatUserControlCover.Controls[1] as ChatUserControl;
user1.ChatFriend = row["username"].ToString();
user1.imgFriendUrl = "../../HttpImageHandler.jpg?username=" + row["username"].ToString();
DataSet dsCM = ucc.GetChatMessages(Session["username"].ToString(), row["username"].ToString());
user1.rpChatDataSource = dsCM;
user1.DataBindForRpChatMessagesToBind();
user1.Visible = true;
}
Master.aspx
<div id="divChatUserControlCover" runat="server">
</div>
Ok I have edited the code and now I have created properties. How do I call the DataBind method for rpChatMessages? I also cant see my usercontrol on page. Why
I'm not sure if your trying to reference the first label or second label. If its the second lable you can't just do chatMessage. you would have to do
((Label)rpChatMessages.FindControl("chatMessage")) due to scope of controls.
When you reference a component inside another component (ie Repeater) the child component no longer belongs to the document (implied this) but rather belongs to the control, ie
this.rpChatMessages { chatMessage }
I think you are just trying to pass a value to one control inside a UserControl if this is correct, declare a public property like this:
ASCX code behind
public string MyProperty
{
get
{
return this.lbl.Text;
}
set
{
this.lbl.Text = value;
}
}
Setting the value to the UserControl
private void BindUserControls()
{
ChatUserControl user1 = divChatUserControlCover.Controls[1] as ChatUserControl;
user1.MyProperty = row["username"].ToString();
Setting the value in the page markup
<uc1:ChatUserControl MyProperty='<%# Eval("some field") %>' ...
Edit 1
Remove that line
public object rpChatDataSource { get { return this.rpChatMessages.DataSource; } set { this.rpChatMessages.DataSource = value; }
And instead add a method
public void BindMyRepeaterOrWhatever(IEnumerable<Yourentity> data)
{
this.myDataBoundControl.DataSource = data;
this.myDataBoundControl.DataBind();
}
You can change the IEnumerable<Yourentity> data for object data but if you can pass a strongly typed enumeration would be better
To my surprise I found why my user control's child controls dont get instantiated. Its because ChatUserControl user1 = new ChatUserControl() doesnt get its child controls initialized.
The proper way to create a new intance of user control is this way....
ChatUserControl user1 = (ChatUserControl)Page.LoadControl("~/ChatUserControl.ascx");

Scriptcontrol - bind client & server properties

Is it possible to bind properties on the client and server side in Scriptcontrol, so when I set property in javascript, change will be visible also in code behind and when I set property in code behind, change will be visible in javascript?
I can't get it work like above - it is set initially, when I set property where scriptcontrol is declared, but when I change it later it is still the same as before...
EDIT: I try to do a ProgressBar for long postbacks in our ASP.NET application. I have tried many options but none works for me... I want to set progress value in code behind and has it updated in view during long task postback.
Code for ScriptControl:
C#:
public class ProgressBar : ScriptControl
{
private const string ProgressBarType = "ProgressBarNamespace.ProgressBar";
public int Value { get; set; }
public int Maximum { get; set; }
protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors()
{
this.Value = 100;
this.Maximum = 90;
var descriptor = new ScriptControlDescriptor(ProgressBarType, this.ClientID);
descriptor.AddProperty("value", this.Value);
descriptor.AddProperty("maximum", this.Maximum);
yield return descriptor;
}
protected override IEnumerable<ScriptReference> GetScriptReferences()
{
yield return new ScriptReference("ProgressBar.cs.js");
}
}
Javascript:
Type.registerNamespace("ProgressBarNamespace");
ProgressBarNamespace.ProgressBar = function(element) {
ProgressBarNamespace.ProgressBar.initializeBase(this, [element]);
this._value = 0;
this._maximum = 100;
};
ProgressBarNamespace.ProgressBar.prototype = {
initialize: function () {
ProgressBarNamespace.ProgressBar.callBaseMethod(this, "initialize");
this._element.Value = this._value;
this._element.Maximum = this._maximum;
this._element.show = function () {
alert(this.Value);
};
},
dispose: function () {
ProgressBarNamespace.ProgressBar.callBaseMethod(this, "dispose");
},
get_value: function () {
return this._value;
},
set_value: function (value) {
if (this._value !== value) {
this._value = value;
this.raisePropertyChanged("value");
}
},
get_maximum: function () {
return this._maximum;
},
set_maximum: function (value) {
if (this._maximum !== value) {
this._maximum = value;
this.raisePropertyChanged("maximum");
}
}
};
ProgressBarNamespace.ProgressBar.registerClass("ProgressBarNamespace.ProgressBar", Sys.UI.Control);
if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
I'll appreciate any way to implement this progress bar...
Personally, I do this often using hidden fields.
Bear in mind that hidden fields are not secure and may have other downfalls, since they don't actually hide their value, just simply do not display it.
ASPX Markup
<asp:HiddenField ID="hiddenRequest" runat="server" ClientIDMode="Static" />
ASPX.CS Code behind
public string HiddenRequest
{
set
{
hiddenRequest.Value = value;
}
get
{
return hiddenRequest.Value;
}
}
Page JAVASCRIPT (with jQuery)
$('#hiddenRequest').val('MyResult');
This way, I can access the same field using one variable as such, accessed both from client side and server side.

asp.net user control default property values

I am in need of some help. I am building a custom web user control which is going to be picking colours.
As of right now, it has two [asp:textbox]es on the page (foregroundColour and backgroundColour).
I want my foreground colour to default to "FFFFFF" and my background colour to default to "000000", AND I the user to be able to specify their own initial values though the tag.
<ucFontChooser id="testchooser" runat="server" foregroundcolor="AABBCC" />
I have two properties that are tied to the textboxes:
[DefaultValue("000000")]
public string ForegroundColor { get { return foregroundColorSelectorHex.Text; } set { foregroundColorSelectorHex.Text = value; } }
[DefaultValue("FFFFFF")]
public string BackgroundColor { get { return backgroundColorSelectorHex.Text; } set { backgroundColorSelectorHex.Text = value; } }
Please note that I am aware that the DefaultValue is only for the visual studio property window and doesn't actually set any value.
However, I have tried to set the default value by in the constructor of the usercontrol to do:
ForegroundColor = "000000"
This gives me an exception, because at the point of the constructor, the foregroundColorSelectorHex is null.
So if I try and setting the default in the OnInit event, or on *Page_Load* then it simply always uses the default I set and the set property value of "AABBCC" is overwritten.
What is the correct way to do what am I trying?
Thank you.
After much debugging, I came up with a solution to do exactly what I need.
public override string ID
{
set
{
base.ID = value;
InitializeProperties();
}
}
protected void InitializeProperties()
{
ForegroundColor = "000000";
BackgroundColor = "ffffff";
EnableBackgroundColor = false;
PrimaryFont = "Arial";
SecondaryFont = "Helvetica";
TertiaryFont = "sans-serif";
}
the .NET framework will call mycontrol.ID = "bla", which is when the user controls subcontrols come into context. It is called BEFORE the containing control/page reads the tags attributes and sets the properties.
Looks hacky, but works great.
I think a complete answer would be too long to answer here, and it's documented at MSDN already.
See this page: http://msdn.microsoft.com/en-us/library/ms972975.aspx
And search for the text "Adding Properties and Methods to a User Control"
(But read the whole article anyway so you understand the details.)
However, from the code in the article, it should you how to return a default value if the property is null. Assuming you have a property named CategoryID, the property should be defined as:
public int CategoryID
{
get
{
object o = ViewState["CategoryID"];
if (o == null)
return 0; // return a default value
else
return (int) o;
}
set
{
ViewState["CategoryID"] = value;
}
}
You can use the same pattern to define the color.
Try keeping the value of the property in the viewstate and then setting the .Text in the Page_PreRender, like so:
public string ForegroundColor
{
get
{
if (ViewState["forecolor"] == null)
{
ViewState["forecolor"] = "000000";
}
return (string) ViewState["forecolor"];
}
set
{
ViewState["forecolor"] = value;
}
}
protected override void OnInit(EventArgs e)
{
this.PreRender += Page_PreRender;
base.OnInit(e);
}
private void Page_PreRender(object sender, EventArgs e)
{
foregroundColorSelectorHex.Text = ForegroundColor;
}
Not sure this will work, but could you do something like this in your page_load:
protected void Page_Load {
if (String.IsNullOrEmpty(ForegroundColor))
ForegroundColor = "FFFFFF";
}
You should initialize the value when it is not postback i.e.
if(!Page.IsPostBack){
//Initialize your values
ForegroundColor = "FFFFFF";
}
Can't you create your foregroundColorSelectorHex and backgroundColorSelectorHex in the constructor ?
public string ForegroundColor {
get { return foregroundColorSelectorHex.Text; }
set { foregroundColorSelectorHex.Text = value; }
}
public string BackgroundColor {
get { return backgroundColorSelectorHex.Text; }
set { backgroundColorSelectorHex.Text = value; }
}
public FontChooser () {
foregroundColorSelectorHex = new ColorSelector();
backgroundColorSelectorHex = new ColorSelector();
ForegroundColor = "FFFFFF";
BackgroundColor = "000000";
}

Resources