小编Ken*_*art的帖子

扩展内置类型的自定义格式功能

我对decimal值有一些相当尴尬的格式要求.简而言之:显示到带有尾随空格的两个小数位,除非第三个小数是5,在这种情况下显示为三个小数位.

这种格式化也需要相当灵活.具体地,不总是期望尾随空间,并且当第三个小数是"5"时,"1/2"可能是优选的.

例子:

  • 1.13将显示为带有空格的"01.13"或没有它的"01.13"
  • 1.315将显示为"01.315"或"01.31½"

我需要在其他不相关的UI部分中一致地使用此逻辑.我暂时将其写为WPF值转换器,但这仅用于演示:

public sealed class PriceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!(value is decimal))
        {
            return DependencyProperty.UnsetValue;
        }

        var decimalValue = (decimal)value;
        var formattedDecimalValue = decimalValue.ToString("#0.000", CultureInfo.InvariantCulture);
        var lastFormattedChar = formattedDecimalValue[formattedDecimalValue.Length - 1];

        switch (lastFormattedChar)
        {
            case '0':
                return formattedDecimalValue.Substring(0, formattedDecimalValue.Length - 1) + " ";
            case '5':
                return formattedDecimalValue.Substring(0, formattedDecimalValue.Length - 1) + "½";
            default:
                return formattedDecimalValue;
        }
    }

    public object ConvertBack(object value, …
Run Code Online (Sandbox Code Playgroud)

.net c# formatting

25
推荐指数
1
解决办法
664
查看次数

反应式扩展是否支持滚动缓冲?

我正在使用反应式扩展将数据整理到100毫秒的缓冲区:

this.subscription = this.dataService
    .Where(x => !string.Equals("FOO", x.Key.Source))
    .Buffer(TimeSpan.FromMilliseconds(100))
    .ObserveOn(this.dispatcherService)
    .Where(x => x.Count != 0)
    .Subscribe(this.OnBufferReceived);
Run Code Online (Sandbox Code Playgroud)

这很好用.但是,我想要的行为与Buffer操作提供的行为略有不同.基本上,如果收到另一个数据项,我想重置计时器.只有当整个100毫秒没有收到数据时我才能处理它.这开启了永不处理数据的可能性,因此我还应该能够指定最大计数.我会想象一下:

.SlidingBuffer(TimeSpan.FromMilliseconds(100), 10000)
Run Code Online (Sandbox Code Playgroud)

我已经环顾四周,在Rx中找不到这样的东西?任何人都可以确认/否认这个吗?

.net c# buffer sliding-window system.reactive

23
推荐指数
2
解决办法
4132
查看次数

如何在LINQ语句中重用表达式?

我喜欢为DRY原因重用表达式,但是如何在LINQ语句中重用表达式?

例如

我有

public static class MyExpressions {
    public static Expression<Func<Product,bool>> IsAGoodProduct() {
        return (p) => p.Quality>3;
    }
}
Run Code Online (Sandbox Code Playgroud)

并且想在LINQ语句中使用它,所以

  var goodProds = from p in dataContext.Products
                  where ????? // how do I use IsAGoodProduct here?
                  select p;
Run Code Online (Sandbox Code Playgroud)

当然,我可以使用IQueryableExtension.Where函数,但这会使连接和其他函数对于更复杂的查询更加困难.

这是可能的还是LINQ的限制?

c# linq lambda

20
推荐指数
2
解决办法
5608
查看次数

WPF ComboBox SelectedItem - 更改为以前的值

我有一个ComboBox,其SelectedItem绑定到ViewModel.

<ComboBox SelectedItem="{Binding SelItem, Mode=TwoWay}" ItemsSource="{Binding MyItems}">
Run Code Online (Sandbox Code Playgroud)

当用户在View ComboBox中选择一个新项目时,我想显示一个提示并确认他们想要进行更改.

在视图模型的SetItem属性设置器中,我显示一个对话框以确认选择.当他们说是的时候,它运作正常.

我的问题是,当用户点击"否"时,我不确定是谁让ComboBox恢复到之前的值.ViewModel中的Property具有正确的旧值,但在View中,ComboBox显示新选择的值.

我希望用户选择一个项目,确认他们要继续使用它,如果他们决定不这样做,我希望ComboBox恢复到上一个​​项目.

我怎么能做到这一点?谢谢!

wpf combobox selecteditem

20
推荐指数
2
解决办法
1万
查看次数

VisualStateManager不像宣传的那样工作

以下问题一直困扰着我好几天,但我只能将它提炼到最简单的形式.考虑以下XAML:

<Window x:Class="VSMTest.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">

    <Window.Resources>
        <Style TargetType="CheckBox">
            <Setter Property="Margin" Value="3"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="CheckBox">
                        <Grid x:Name="Root">
                            <Grid.Background>
                                <SolidColorBrush x:Name="brush" Color="White"/>
                            </Grid.Background>

                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup Name="CheckStates">
                                    <VisualStateGroup.Transitions>
                                        <VisualTransition To="Checked" GeneratedDuration="00:00:03">
                                            <Storyboard Name="CheckingStoryboard">
                                                <ColorAnimationUsingKeyFrames Storyboard.TargetName="brush" Storyboard.TargetProperty="Color">
                                                    <DiscreteColorKeyFrame KeyTime="0" Value="LightGreen"/>
                                                </ColorAnimationUsingKeyFrames>
                                            </Storyboard>
                                        </VisualTransition>

                                        <VisualTransition To="Unchecked" GeneratedDuration="00:00:03">
                                            <Storyboard Name="UncheckingStoryboard">
                                                <ColorAnimationUsingKeyFrames Storyboard.TargetName="brush" Storyboard.TargetProperty="Color">
                                                    <DiscreteColorKeyFrame KeyTime="0" Value="LightSalmon"/>
                                                </ColorAnimationUsingKeyFrames>
                                            </Storyboard>
                                        </VisualTransition>
                                    </VisualStateGroup.Transitions>

                                    <VisualState Name="Checked">
                                        <Storyboard Name="CheckedStoryboard" Duration="0">
                                            <ColorAnimationUsingKeyFrames Storyboard.TargetName="brush" Storyboard.TargetProperty="Color">
                                                <DiscreteColorKeyFrame KeyTime="0" Value="Green"/>
                                            </ColorAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>

                                    <VisualState Name="Unchecked">
                                        <Storyboard Name="UncheckedStoryboard" Duration="0">
                                            <ColorAnimationUsingKeyFrames Storyboard.TargetName="brush" …
Run Code Online (Sandbox Code Playgroud)

silverlight wpf animation transitions

18
推荐指数
1
解决办法
4801
查看次数

检查当前线程是否拥有锁

假设我有以下代码:

public class SomeClass()
{
    private readonly object _lock = new object();

    public void SomeMethodA()
    {
        lock (_lock)
        {
            SomeHelperMethod();

            //do something that requires lock on _lock
        }
    }

    public void SomeMethodB()
    {
        lock (_lock)
        {
            SomeHelperMethod();

            //do something that requires lock on _lock
        }
    }

    private void SomeHelperMethod()
    {
        lock (_lock)
        {
            //do something that requires lock on _lock
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

锁定内部SomeHelperMethod似乎是多余和浪费的,因为所有呼叫者都已经锁定.但是,简单地删除锁SomeHelperMethod似乎很危险,因为我们以后可能会重构代码并忘记_lock在调用之前锁定对象SomeHelperMethod.

理想情况下,我可以通过断言当前线程在_lock内部拥有一个锁来解决这个问题SomeHelperMethod:

private void SomeHelperMethod() …
Run Code Online (Sandbox Code Playgroud)

.net multithreading locking

17
推荐指数
2
解决办法
4990
查看次数

数据绑定POCO属性

是否有任何数据绑定允许之间的绑定框架(BCL或其他方式)的任何两个CLR性能实现INotifyPropertyChangedINotifyCollectionChanged?似乎应该可以做这样的事情:

var binding = new Binding();
binding.Source = someSourceObject;
binding.SourcePath = "Customer.Name";
binding.Target = someTargetObject;
binding.TargetPath = "Client.Name";
BindingManager.Bind(binding);
Run Code Online (Sandbox Code Playgroud)

在哪里someSourceObjectsomeTargetObject只是实施的POCO INotifyPropertyChanged.但是,我没有意识到BCL对此有任何支持,并且不确定是否存在允许这样做的现有框架.

更新:鉴于没有现有的库,我已经自己写了自己的库.它可以在这里找到.

谢谢

.net c# data-binding poco system.componentmodel

17
推荐指数
2
解决办法
4177
查看次数

文件共享无法按预期工作

我有一个文件共享问题,我的进程正在尝试读取日志文件,而它当前仍由NLog打开.在诊断问题时,我发现了令人惊讶的事情.以下失败:

using (var fileStream1 = new FileStream("test.file", FileMode.Append, FileAccess.Write, FileShare.Read))
using (var fileStream2 = new FileStream("test.file", FileMode.Open, FileAccess.Read, FileShare.Read))
{
}
Run Code Online (Sandbox Code Playgroud)

第二个FileStream构造函数调用失败:

System.IO.IOException was unhandled
  Message=The process cannot access the file 'c:\...\test.file' because it is being used by another process.
  Source=mscorlib
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
       at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess …
Run Code Online (Sandbox Code Playgroud)

.net c# file-sharing file-security

14
推荐指数
1
解决办法
6408
查看次数

在本机应用和网站之间共享凭据

我正在处理的应用程序允许用户登录启用OAuth的后端.因此,应用程序仅对身份验证令牌和用户元数据有用,而不是用户的凭据.

在应用程序中,用户可以点击在浏览器中打开链接的链接.这些资源也受OAuth保护,在登录本机应用程序期间获得的令牌也与Web相关.

我希望用户的凭据以标准OAuth方式从本机应用程序流向Web浏览器(通过将其作为Authorization标题包含在内).

似乎Android通过其共享凭据功能促进了这一点,但我找不到iOS的等价物.我确实找到了共享的Web凭据功能,但这似乎需要了解用户的凭据.

如何将OAuth令牌从我的原生应用程序流向它打开的Web浏览器?

security safari ios oauth-2.0

13
推荐指数
2
解决办法
3595
查看次数

Merged ObservableCollection

我有两个ObservableCollections,我需要在一个ListView控件中一起显示它们.为此,我创建了MergedCollection,它将这两个集合显示为一个ObservableCollection.这样我就可以将ListView.ItemsSource设置为我的合并集合,并列出两个集合.添加工作正常,但当我尝试删除项目时,显示未处理的异常:

An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll
Additional information: Added item does not appear at given index '2'.
Run Code Online (Sandbox Code Playgroud)

MergedCollection的代码如下:

public class MergedCollection : IEnumerable, INotifyCollectionChanged
{
    ObservableCollection<NetworkNode> nodes;
    ObservableCollection<NodeConnection> connections;

    public MergedCollection(ObservableCollection<NetworkNode> nodes, ObservableCollection<NodeConnection> connections)
    {
        this.nodes = nodes;
        this.connections = connections;

        this.nodes.CollectionChanged += new NotifyCollectionChangedEventHandler(NetworkNodes_CollectionChanged);
        this.connections.CollectionChanged += new NotifyCollectionChangedEventHandler(Connections_CollectionChanged);
    }

    void NetworkNodes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        CollectionChanged(this, e);
    }

    void Connections_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        CollectionChanged(this, e);
    }

    #region IEnumerable Members

    public IEnumerator GetEnumerator()
    {
        for …
Run Code Online (Sandbox Code Playgroud)

c# collections wpf merge observablecollection

12
推荐指数
1
解决办法
1万
查看次数