I have a main form with a textBox1 with string value : asd
namespace Crystal
{
public partial class MainForm : Form
{
//here is a textBox1 with text "asd"
}
}
I want to change this textBox1 text from this class:
namespace Crystal.Utilities
{
public class Logging
{
//textBox1.Text = "dsa";
}
}
The problem is, I cant change the value of textBox1 from the Logging class, because it doesnt exists there :/ How to do this?
Don't need to expose the entire TextBox - Don't want others to mess with other things than just the text, and I think it's more readable and simple to just call a method that does that, instead of accessing the TextBox directly.
namespace Crystal
{
public partial class MainForm : Form
{
public void setTextBox1Text(string newText)
{
TextBox1.Text=newText
}
}
}
namespace Crystal.Utilities
{
public class Logging
{
mainForm.SetTextBox1Text("new text");
}
}
You have to create a public property (supposing you're writing C#) or a method. Then access it from the other place.
namespace Crystal
{
public partial class MainForm : Form
{
//here is a textBox1 with text "asd"
public TextBox MyTextBox {
get { return textBox1; }
}
}
}
namespace Crystal.Utilities
{
public class Logging
{
var foo = MainForm; // Get an instance of your MainForm here somehow.
foo.MyTextBox.Text = "dsa";
}
}
Related
I am creating UWP app using Template 10. I have created user control like this.
<my:DeviceInfoUserControl OnEndpointTypeChange="{Binding OnEndpointTypeChangeCommand}" Component="{Binding DeviceManagementViewModel,Mode=TwoWay}"></my:DeviceInfoUserControl>
I have Radio Buttons on User Control. I have added User Control on Multiple screens.
This user control has its own ViewModel as well as Some Dependency Properties as follows:
public class DeviceManagementViewModel : ViewModelBase
{
}
public sealed partial class DeviceInfoUserControl : UserControl
{
public bool IsToggled = true;
public DeviceInfoUserControl()
{
this.InitializeComponent();
}
public static readonly DependencyProperty OnEndpointTypeChangeProperty =
DependencyProperty.Register(
"OnEndpointTypeChange",
typeof(ICommand),
typeof(DeviceInfoUserControl), new PropertyMetadata(null));
public ICommand OnEndpointTypeChange
{
get { return (ICommand)GetValue(OnEndpointTypeChangeProperty); }
set { SetValue(OnEndpointTypeChangeProperty, value); }
}
public static readonly DependencyProperty ComponentProperty = DependencyProperty.Register("Component", typeof(DeviceManagementViewModel), typeof(DeviceInfoUserControl), new PropertyMetadata(null));
public DeviceManagementViewModel Component
{
get { return (DeviceManagementViewModel)GetValue(ComponentProperty); }
set { SetValue(ComponentProperty, value); }
}
}
I want to preserve Radio Button Selection across all screens. How should I achieve this?
You have to ensure that the same ViewModel instance is used for all control instance. The XAML way is always create new instance:
<Page.DataContext>
<vm:DetailPageViewModel x:Name="ViewModel" />
</Page.DataContext>
In the Template10's Bootstrapper class with the ResolveForPage method override, you can inject ViewModel's after the page navigation through a custom logic, or through dependency injection LINK
Don't know its better way or not but I have achieved this by making Singletone Viewmodel.
public class DeviceManagementViewModel : ViewModelBase
{
public static readonly DeviceManagementViewModel _instance = new DeviceManagementViewModel ();
private DeviceManagementViewModel ()
{
}
/*Properties and Methods */
}
In Parent Screen ViewModel I have created following property
private DeviceManagementViewModel _deviceManagementViewModel;
public DeviceManagementViewModel DeviceManagementViewModel1
{
get { return _deviceManagementViewModel; }
set { Set(ref _deviceManagementViewModel, value); }
}
I have Instantiated property in Constructor:
public ConfigurationViewModel()
{
DeviceManagementViewModel1 = DeviceManagementViewModel._instance;
}
And on User Control:
<my:DeviceInfoUserControl OnEndpointTypeChange="{Binding OnEndpointTypeChangeCommand}" Component="{Binding DeviceManagementViewModel1,Mode=TwoWay}"></my:DeviceInfoUserControl>
I've initiated a class within my form like so:
namespace StartScreen
{
public partial class SetupScreen : Form
{
Battleship myBattleship;
Control myObject;
public SetupScreen()
{
InitializeComponent();
myBattleship = new Battleship();
//Create Class Object
}
}
}
I want to access the class object myBattleship in another form, I can pass it through however when I do I can't make it public so it can be accessed everywhere from the new form. How would I go about doing this?
in Main Form:
public class Battleship
{
//define what you want///
}
public myBattleship = new Battleship();
in Form you want to use myBattleship:
MainForm.myBattleship;
EF has generated for me some partial classes, each with a constructor, but it says not to touch them (example below), now if I make my own secondary partial class and I want to have a constructor that automatically sets some of the fields how do I do so as it would conflict?
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Breakdown.Models
{
using System;
using System.Collections.Generic;
public partial class Call
{
public Call()
{
this.Logs = new HashSet<Log>();
}
...
}
}
Partial methods can help you here, in the T4 Templates define a body-less partial method and call that inside the constructor.
public <#=code.Escape(entity)#>()
{
...
OnInit();
}
partial void OnInit();
Then in your partial class define the partial method and place inside that what you want to do in the constructor. If you don't want to do anything then you don't need to define the partial method.
partial class Entity()
{
partial void OnInit()
{
//constructor stuff
...
}
}
http://msdn.microsoft.com/en-us/library/vstudio/6b0scde8.aspx
This is not possible.
Partial classes are essentially parts of the same class.
No method can be defined twice or overridden (same rule apply for the constructor also)
But You can use below mentioned Workaround :
//From file SomeClass.cs - generated by the tool
public partial class SomeClass
{
// ...
}
// From file SomeClass.cs - created by me
public partial class SomeClass
{
// My new constructor - construct from SomeOtherType
// Call the default ctor so important initialization can be done
public SomeClass(SomeOtherType value) : this()
{
}
}
for more information check Partial Classes, Default Constructors
I hope this will help to you.
I wanted to do the same recently and ended up modifying the T4 template so I could implement my own parameterless constructor manually. To accomplish this you can remove the constructor from the generated classes and move the instantiation of collections etc to outside the constructor so this:
public Call()
{
this.Logs = new HashSet<Log>();
}
becomes this:
private ICollection<Log> logs = new HashSet<Log>();
public virtual ICollection<Log> Logs
{
get { return this.logs; }
set { this.logs = value; }
}
The drawback I suppose is that the generated classes are not as "clean". That is you can't just have auto-implemented properties for your complex/nav types.
In your model.tt file you can prevent the constructor generation by removing the below code, commenting it out or by just putting in a false into the conditional so it never gets executed:
if (propertiesWithDefaultValues.Any() || complexProperties.Any())
{
#>
public <#=code.Escape(complex)#>()
{
<#
foreach (var edmProperty in propertiesWithDefaultValues)
{
#>
this.<#=code.Escape(edmProperty)#> =
<#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>;
<#
}
foreach (var complexProperty in complexProperties)
{
#>
this.<#=code.Escape(complexProperty)#> = new
<#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>();
<#
}
#>
}
Then below this you need to do some modification where properties are generated for your complex and navigation types. Add a private var with object instantiation and a property for accessing the private var for each of these eg:
if (complexProperties.Any())
{
foreach(var complexProperty in complexProperties)
{
//generate private var + any instantiation
//generate property for accessing var
}
}
Depending on the complexity of your model there may be other areas you need to modify. Hopefully this gets you started.
If I well understand the question, you need this constructor when creating a new entity, that is an entity that was not persisted before.
My case was to set a default value to all datetime, that is initalize them to "the begining of time" : 1900-01-01.
In this case I use an entity factory
public static T GetNewEntity<T> () {
T e;
try {
e = Activator.CreateInstance<T>();
} catch {
e = default(T);
}
SetDefaults(e);
return e;
}
Each time I need a new Entity I use
Entity e = GetNewEntity<Entity>();
with SetDefaults as :
public static void SetDefaults (object o) {
Type T = o.GetType();
foreach ( MemberInfo m in T.GetProperties() ) {
PropertyInfo P = T.GetProperty(m.Name);
switch ( Type.GetTypeCode(P.PropertyType) ) {
case TypeCode.String :
if ( P.GetValue(o, null) == null )
P.SetValue(o, String.Empty, null);
break;
case TypeCode.DateTime :
if ( (DateTime)P.GetValue(o, null) == DateTime.MinValue )
P.SetValue(o, EntityTools.dtDef, null);
break;
}
}
}
full code is here
It could be rewrittent to consider the entity type and so on...
Add a base class:
public class CallBase
{
protected CallBase()
{
Initialize();
}
protected abstract void Initialize();
}
Add the partial class implementation in another file
public partial class Call: CallBase
{
protected override void Initialize();
{
...
}
}
The drawback is that the Initialization method will be called before the all collection creature.
I'm working with WF.
I made a custom activity called Draft_Doc:
public sealed class Draft_Doc : CodeActivity<string>
{
protected override string Execute(CodeActivityContext context)
{
C.Send_Task_Msg(unique_name, "Draft");
return "Draft";
}
}
I made another activity that contains a bookmark.
public sealed class WaitingTheApproval : NativeActivity
{
WorkflowInstanceProxy instance;
Service1Client C = new Service1Client();
public InArgument<string> previous_stage { get; set; }
public string stageName;
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
base.CacheMetadata(metadata);
metadata.AddDefaultExtensionProvider<MyExtension>(() => new MyExtension());
//RuntimeArgument argSql = new RuntimeArgument("SqlConnectionString", typeof(String), ArgumentDirection.In);
}
protected override bool CanInduceIdle
{
get { return true; }
}
protected override void Execute(NativeActivityContext context)
{
var bookmark = context.CreateBookmark("MyBookmark", BookmarkResumed);
var extension = context.GetExtension<MyExtension>();
instance = extension._instance;
stageName = context.GetValue(this.previous_stage);
stageName = previous_stage.Get(context);
WaitSome(bookmark);
}
}
What I want is, when I drag and drop these two activities in rehosted workflow. I want to drag Draft_Doc first then I will link the WaitingTheApproval with it.
So, I want the return value from Draft_Doc set in the InArgument previous_stage in WaitingTheApproval at runtime.
Anyhelp?
There is no way to pass a value from one activity to another directly. you should assign the value to a Variable in the first activity and use the variable which has been assigned in the second activity.
In the StockTraderRI sample code the ViewModel is injected by MEF using a property:
[Export(typeof(IOrdersView))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class OrdersView : UserControl, IOrdersView
{
public OrdersView()
{
InitializeComponent();
}
[Import]
[SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly", Justification = "Needs to be a property to be composed by MEF")]
public IOrdersViewModel ViewModel
{
set { this.DataContext = value; }
}
}
What I wonder is: why not use an ImportingConstructor like this to inject the ViewModel:
[Export(typeof(IOrdersView))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class OrdersView : UserControl, IOrdersView
{
[ImportingConstructor]
public OrdersView(IOrdersViewModel ViewModel)
{
InitializeComponent();
this.DataContext = ViewModel;
}
}
Is there a special feature, problem or reason I miss why the StockTraderRI sample does use a Property instead of a paramter to the ctor?
Because types partially defined in XAML don't play well with parametrized constructors. XAML is built on the "create a blank object and fill in the properties afterwards" paradigm.