I am working in Namibia. Namibia is not an option on the Windows Region and Language settings, but share most cultural specifics with South Africa, so we select English South Africa and then customize the currency symbol to be "N$" (Namibian Dollars) and not "R" (South African Rand).
However, I can't convince WPF to use the customized currency. Using string.format("{0:c}", foo) in code works fine, but using {Binding Path=SomeCurrencyValue, StringFormat=c}` in XAML still uses the "R" symbol and not the custom "N$" symbol.
In App.xaml.cs I set the Application Culture with the following code:
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(System.Globalization.CultureInfo.CurrentCulture.LCID, true);
FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement),
new FrameworkPropertyMetadata(
System.Windows.Markup.XmlLanguage.GetLanguage(
System.Globalization.CultureInfo.CurrentUICulture.IetfLanguageTag)));
As demonstration, here is some XAML code that shows the problem:
<StackPanel>
<TextBlock>
Formatted in XAML with: <LineBreak/>
Text="{Binding Path=SomeCurrencyValue, StringFormat=c}" <LineBreak/>
Result:
</TextBlock>
<TextBox Text="{Binding Path=SomeCurrencyValue, StringFormat=c, Mode=OneWay}"
Margin="5"/>
<TextBlock>
Formatted in code with: <LineBreak/>
return string.Format("{0:c}", SomeCurrencyValue); <LineBreak/>
Result:
</TextBlock>
<TextBox Text="{Binding Path=SomeCurrencyString, Mode=OneWay}"
Margin="5"/>
</StackPanel>
The DataContext for the above View contains the following:
public double SomeCurrencyValue
{
get { return 34.95; }
}
public string SomeCurrencyString
{
get
{
return string.Format("{0:c}", SomeCurrencyValue);
}
}
And the result looks like this:
I know there is a similiar question here, but I was hoping to get better answers with a more complete question. I am mostly working on financial applications for Namibian clients, so this is quite a serious issue for me - if there is no way to do this with .NET 4.0, I would consider filing a bug report, but I just wanted to check here first.
EDIT:
Just opened up the bounty on this question. I'm hoping for either a solution that isn't a rediculous workaround, or confirmation that this is a bug and should be filed as such.
One solution to this is to create this Namibian CultureInfo, so its fully recognized by all .NET layers. Here is a code that does it:
public static void RegisterNamibianCulture()
{
// reference the sysglobl.dll assembly for this
CultureAndRegionInfoBuilder namibianCulture = new CultureAndRegionInfoBuilder("en-NA", CultureAndRegionModifiers.None);
// inherit from an existing culture
namibianCulture.LoadDataFromCultureInfo(new CultureInfo("en-za"));
namibianCulture.CultureEnglishName = "Namibia";
namibianCulture.RegionEnglishName = "Namibia";
namibianCulture.CultureNativeName = "Namibia"; // you may want to change this
namibianCulture.RegionNativeName = "Namibia"; // you may want to change this
// see http://en.wikipedia.org/wiki/ISO_3166-1, use user-defined codes
namibianCulture.ThreeLetterISORegionName = "xna"; // I use x as 'extended' and 'na' as namibia
namibianCulture.TwoLetterISORegionName = "xn";
namibianCulture.ThreeLetterWindowsRegionName = namibianCulture.ThreeLetterISORegionName;
// see http://www.currency-iso.org/dl_iso_table_a1.xml
namibianCulture.ISOCurrencySymbol = "nad";
namibianCulture.CurrencyEnglishName = "Namibia Dollar";
namibianCulture.CurrencyNativeName = "Namibia Dollar"; // you may want to change this
// this is were you build something specific, like this symbol you need
namibianCulture.NumberFormat.CurrencySymbol = "N$";
// you'll need admin rights for this
namibianCulture.Register();
}
public static void UnregisterNamibianCulture()
{
CultureAndRegionInfoBuilder.Unregister("en-NA");
}
Once you have called the Register function once on a given machine (you will need to install this culture on end user machines), you can now use your initial WPF startup code, just change it like this:
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-NA");
And everything should work as expected. You can also use standard language tags and all that jazz, since en-NA is now recognized.
I had the same problem and I started from Simon's answer (thank you, Simon) making some modifications in order to get the user configuration (Region and Language in Control Panel) every time the application is launched, not the culture default.
My code look like this one
public MainWindow()
{
CreateAndRegisterLocalizedCulture();
this.Language = XmlLanguage.GetLanguage(customCultureName);
InitializeComponent();
DataContext = new ViewModel();
}
private void CreateAndRegisterLocalizedCulture()
{
CultureAndRegionInfoBuilder customCulture = new CultureAndRegionInfoBuilder(customCultureName, CultureAndRegionModifiers.None);
// Inherits from the current culture and region, may be configured by the user
customCulture.LoadDataFromCultureInfo(CultureInfo.CurrentCulture);
customCulture.LoadDataFromRegionInfo(RegionInfo.CurrentRegion);
// Not needed for the culture sake but...
customCulture.CultureEnglishName = CultureInfo.CurrentCulture.EnglishName + "-Customized";
customCulture.CultureNativeName = CultureInfo.CurrentCulture.NativeName + "-Customized";
// If the custom culture is already registered an unregistration is needed
// otherwise the following Register() call will generate an exception
if (CultureInfo.GetCultures(CultureTypes.UserCustomCulture).Where(ci => (ci.Name == customCulture)).Count() != 0)
{
// Admin rights are needed here
CultureAndRegionInfoBuilder.Unregister(customCulture);
}
// Admin rights are needed here
customCulture.Register();
}
It works fine to me but there are two problems in this approach:
In windows 7+ you need to start the application with Administrator rights as it will create a new culture file in C:\Windows\Globalization with the name you give to your custom culture
The Unregister method does not delete the above create file but it renames it as xyz.tmp0 and, with a logic I didn't get, time to time it creates more tmp file copies (xyz.tmp1, xyz.tmp2, ...). At least it is how it works in my pc.
Something that is not really a problem but a bit weird is that, once I change my regional settings in the control panel, I have to start my application twice before I see the modification. I can survive :)
Related
I'm currently trying to build a UWP app that points to a SqlServer, and thru much research, determined that my best plan of attack was to create a WebService and make EF Calls to "CRUD" the dbase.
I found a good tutorial that helped a lot, however, I'm still new at this so seeing what some else did, and adapting is a learning experience. So it has caused a few questions to come up, that I have yet to solve.
These are my question;
HostName below is an INT in the Database and POGO Class.. So I'm getting the "cannot implicitly convert type 'int' to 'string'" error. How do I resolve this? Do I use StringFormatConverter that is part of the Template I'm using?
The last value, EMV is a boolean value. It is currently pointing to a Toggleswitch and is pointing to the IsOn property of the Control. Will that resolve correctly?
Lastly, I would like to keep as much of my code adherent to the MVVM format. So If I move the below code below from Code Beyond to the ViewModel would that perform better?
Here is the Code Behind inside the Click Event...
private async void Save_Click(object sender, RoutedEventArgs e)
{
var tblDevice = new Device { HostName = hostNameTB.Text, Server =serverIPTB.Text, RouterName = routerNameTB.Text, IP = iPTB.Text, Gateway =gatewayTB.Text, Hardware = hardwareTB.Text, EMV = eMVTB.IsOn};
var deviceJson = JsonConvert.SerializeObject(tblDevice);
var client = new HttpClient();
var HttpContent = new StringContent(deviceJson);
HttpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("Application/json");
await client.PostAsync("http://localhost:2463/api/Devices", HttpContent);
Frame.GoBack();
}
Here is the XAML
<TextBox Name="hostNameTB" />
<TextBox Name="serverIPTB" />
<TextBox Name="routerNameTB" />
<TextBox Name="iPTB" />
<TextBox Name="gatewayTB" />
<TextBox Name="hardwareTB" />
<ToogleSwitch Header="EMV" IsOn="False" Name="eMVTB" OffContent="UnConfigured" OnContent="Configured" />
1 Int32.Parse(hostNameTB.Text) or via the Converter your choice.
2 Yes it will come thru as a 1 or a 0, true/false etc. In the DB I assume this a
BIT type?
3) it will perform the same only difference is testability
I have a Windows Phone page code that is shared by multiple applications.
At the top of the page, I show the title of the application, like so:
Is it possible to make the text be bound to the application title as defined in the application's assembly?
I realise that I could do this by code by reading the title in the assembly and then doing something like:
this.ApplicationTitle.Text = title;
I was hoping that the title as defined in the assembly could be accessed with some magic like:
Text={assembly title}" directly from within the xaml.
Thanks
Create a property called ApplicationTitle that returns that name of the application like the following, and then bind to it in XAML:
public string ApplicationTitle
{
get { return System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; }
}
(You can use a relative binding source if you can't or don't want to use the data context.)
edit:
I just realized that my method involved security considerations since GetName is a method that is [Security Critical]. And I got a MethodAccessException stating: Attempt to access the method failed: System.Reflection.Assembly.GetName()
So here's another way to get the assembly name and return it in a property by using the AssemblyTitle attribute.
public string ApplicationTitle
{
get
{
System.Reflection.AssemblyTitleAttribute ata =
System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(
typeof(System.Reflection.AssemblyTitleAttribute), false)[0] as System.Reflection.AssemblyTitleAttribute;
return ata.Title;
}
}
To bind in XAML, you can use this:
Text="{Binding ElementName=LayoutRoot, Path=Parent.ApplicationTitle}"
I'm having a hard time getting a custom activity designer of mine to display in the workflow designer. My activity includes an activity func, and I've already found a number of blogs posts dealing with them here, here, here and here.
The custom activity has an ActivityFunc<> as an input argument, and I need to expose the func in a designer as drop zone in which the user can place an "inner" activity (à la TransactionScope).
The custom activity is authored in XAML, and the func's declaration looks like this:
<x:Property Name="CompletionTest" Type="ActivityFunc(sdscmt:DmeTask, sdsav:WfPatient, sdscmc:DmeClinicalElement, x:Boolean)" />
The XAML also contains an InvokeFunc<> activity matching the CompletionTest property.
The activity designer follows the recommendations outlined in the blog posts mentionned above. In particular, it overrides OnModelItemChanged to initialize the CompletionTest property:
if (this.ModelItem.Properties["CompletionTest"].Value == null)
{
this.ModelItem.Properties["CompletionTest"].SetValue(
new ActivityFunc<DmeTask, WfPatient, DmeClinicalElement, bool>()
{
Argument1 = new DelegateInArgument<DmeTask>
{
Name = "task"
},
Argument2 = new DelegateInArgument<WfPatient>
{
Name = "patient"
},
Argument3 = new DelegateInArgument<DmeClinicalElement>
{
Name = "element"
},
Result = new DelegateOutArgument<bool>
{
Name = "success"
},
});
}
The designer's XAML looks like this:
<sap:ActivityDesigner x:Class="SoftInfo.Dme.ServicesDme.Workflow.Design.PerformTaskDesigner" ... >
<StackPanel>
<sap:WorkflowItemPresenter AllowedItemType="{x:Type sa:Activity}" Background="Transparent" MinWidth="150" MinHeight="100" HintText="Drop the completion test here" Margin="5,5,5,5" Item="{Binding Path=ModelItem.CompletionTest.Handler, Mode=TwoWay}" />
</StackPanel>
</sap:ActivityDesigner>
After all this, whenever I place an instance of my custom activity into a workflow, I get a red box labelled "Could not generate view for PerformTask" where my designer should appear. The box's tooltip indicates that an exception occurred from within the designer :
System.Windows.Markup.XamlParseException: A 'Binding' cannot be set on the 'Item' property of type 'WorkflowItemPresenter'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
I don't understand what I'm doing wrong. I've used WorkflowItemPresenter many times before, and this is the first time I've gotten this binding error.
That's kind of a messed up way to go about this. The error may be incorrect; the inner exception would tell the tale I'd wager (sorry, listening to Game of Thrones while I work today).
I implement IActivityTemplateFactory to configure my activity delegates:
public sealed class MyActivity: NativeActivity, IActivityTemplateFactory
{
public const string ChildArgumentName = "theArgument";
public ActivityFunc<object, bool> Child { get; set; }
Activity IActivityTemplateFactory.Create(System.Windows.DependencyObject target)
{
return new MyActivity()
{
Child = new ActivityFunc<Capture, bool>
{
Argument = new DelegateInArgument<object>(ChildArgumentName )
}
};
}
}
Notice a couple things here. Yes, the design surface instantiates an instance of your Activity only to use it to create another instance of the same Activity (configured properly, of course), but this method is bulletproof. You can, if requirements dictate, move your implementation of IATF elsewhere, but if it doesn't matter who cares?
Notice that I declare in my Activity's design what the name of the Func's argument will be. You can do this in a more generic fashion (custom attributes, etc), but if your Activities fit together in a predictable fashion, I have found this is the simplest manner to automatically wire up child Activities with their parents. YMMV.
In the designer, its similar:
<sap:WorkflowItemPresenter
HintText="Add child here"
Item="{Binding ModelItem.Child.Handler}" />
that's all you need. If the signature of the Activity doesn't match, it won't fit. The child also takes advantage of IATF to bind itself to its parent:
public sealed class ChildActivity : NativeActivity<bool>, IActivityTemplateFactory
{
public InArgument<object> Target { get; set; }
Activity IActivityTemplateFactory.Create(System.Windows.DependencyObject target)
{
return new ChildActivity
{
Target = new VisualBasicValue<object>(MyActivity.ChildArgumentName)
};
}
}
If you expect your child Activity to be dropped on different targets, you might have to do some annoying inspection of the target DependencyObject, which will allow you to inspect the current workflow tree. (Please note, I'm not 100% familiar with the implicit conversion behavior of VisualBasicValue, so you might have some compiler errors with the above code!)
Another option if you have to be extra tricky (drop an Activity from the toolbox, then drag it somewhere else where you will have to re-do your inspection) is to inspect the current state of the workflow from within CacheMetadata. I haven't done this, but I believe you can and update your registrations with the design surface to reflect the current state of the workflow.
Thread.CurrentThread.CurrentCulture = New CultureInfo("sv-SE")
Thread.CurrentThread.CurrentUICulture = New CultureInfo("sv-SE")
Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyGroupSeparator = " "
Thread.CurrentThread.CurrentUICulture.NumberFormat.CurrencyGroupSeparator = " "
Im trying to do:
<TextBlock Text={Binding decimalValue, StringFormat=c2}/>
It sets the culture properly and adds the "kr" which is the swedish currency symbol. However, doesnt honor the group separator setting. Even if I set it to "-" or whatever it doesnt work.
Big questionmark? Bug?
I am not sure if you were able to work around this problem, but since nobody answered, I will.
For starters, I am not sure if your backing code runs in the same thread as presentation layer; probably not, that is I believe Silverlight creates its own visual thread. In other words setting thread-wide CultureInfo will not resolve your problem.
There are (at least) two ways to resolve this issue:
1. Play with StringFormat attribute to set custom format.
2. Create dynamic property in the backing code which will format the value for you. Please find this imperfect example:
public decimal Quote { get; set; }
// Formats value of Quote property
public string FormattedQuote
{
get
{
CultureInfo swedishCulture = new CultureInfo("sv-SE");
swedishCulture.NumberFormat.CurrencyGroupSeparator = " ";
return Quote.ToString("c2", swedishCulture);
}
}
And in your XAML code, you do not need specify format, so you would only do this:
<TextBlock Name="textBlock1" Text="{Binding FormattedQuote}" DataContext="{Binding ElementName=textBlock1}" />
Suppose you have WPF Window composed of many elements that are using DataTemplates / ControlTemplates (ItemControls ... )
But you want to see how every DataTemplate looks like in VS Designer.
What more, if you define a ControlTemplate from as a Template located in another file to be able to view it with the content.
Something like MasterPage and ChildElements in ASP.NET
You can always see what elements have you put together.
Is this possible in WPF too?
Otherwise.. every change I make to the DataTemplate can be seen after a long-time-consuming compilation and start.
Thank you guys..
Stefan,
I think that you can do this by creating Design Time class as described in the link below:
http://karlshifflett.wordpress.com/2008/10/11/viewing-design-time-data-in-visual-studio-2008-cider-designer-in-wpf-and-silverlight-projects/
Hope this helps.
To do this extremely simply, just set a DataContext in your constructor:
public MyUserControl()
{
#if !RELEASE
//DataContext = new CustomerList { Customers = new [] {
// new Customer { Name = "Contoso", ZipCode = 12345 },
// new Customer { Name = "NorthWind", ZipCode = 12345 },
//}};
#endif
InitializeComponent();
...
}
Notice the fact that the code is commented out. When you want to see data, just uncomment the code. The #if !RELEASE protects you from accidentally including the sample data in your release (and from spending any CPU loading it).
If your sample data is big, just put it in XML or in a database and load it:
public MyUserControl()
{
#if !RELEASE
//DataContext = XmlSerializerManager.Deserialize<CustomerList>(
// File.ReadAllBytes("CustomerSampleData.xml"));
#endif
InitializeComponent();
...
}
In either case, the sample data will show up in the designer whenever you uncomment the code. When executing your application it will be replaced with the real data.