UpdateSourceTrigger
0.在一个项目中在用到绑定的时候一直有一个问题,虽然设置了Mode=TwoWay,界面的值修改了,但是后天绑定的值没有变化。最终发现了问题,在于UpdateSourceTrigger属性的使用,通过这个属性指定什么时刻去通知源数据改变值。默认是失去焦点触发,当然也可以根据程序需要,更改触发条件。
例如:控件属性="{Binding SettingMarkContent,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
Binding Mode 
oneWay:使用 OneWay 绑定时,每当源发生变化,数据就会从源流向目标。

OneTime: 绑定也会将数据从源发送到目标;但是,仅当启动了应用程序或 DataContext 发生更改时才会如此操作,因此,它不会侦听源中的更改通知。

OneWayToSource: 绑定会将数据从目标发送到源。

TwoWay: 绑定会将源数据发送到目标,但如果目标属性的值发生变化,则会将它们发回给源。

Default: binding的模式根据实际情况来定,如果是可编辑的就是TwoWay,只读的就是OneWay.

上面的例子不设Mode时,默认的就是Default.

1.应用程序中正在运行线程时,System.Windows.Application.Current.Shutdown();关闭应用程序有异常,使用下边方法。
close的时候子线程还处于active状态吧。。完全退出用
System.Environment.Exit(System.Environment.ExitCode);
2.托盘窗口

this.notifyIcon = new NotifyIcon();
            this.notifyIcon.BalloonTipText = "running in background";
            this.notifyIcon.ShowBalloonTip(2000);
            this.notifyIcon.Text = "running in background";
            this.notifyIcon.Icon = new System.Drawing.Icon(DirectoryManager.AppPath + "\\UpDownload_48x48.ico");
            this.notifyIcon.Visible = true;
            this.Icon = new BitmapImage(new Uri(@"UpDownload_48x48.ico", UriKind.Relative));
            //打开菜单项
            System.Windows.Forms.MenuItem open = new System.Windows.Forms.MenuItem("Open");
            open.Click += new EventHandler(Show);
            //退出菜单项
            System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("Exit");
            exit.Click += new EventHandler(Close);
            //关联托盘控件
            System.Windows.Forms.MenuItem[] childen = new System.Windows.Forms.MenuItem[] { open, exit };
            notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(childen);

            this.notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler((o, e) =>
            {
                if (e.Button == MouseButtons.Left) this.Show(o, e);
            });

private NotifyIcon notifyIcon;
        private void Show(object sender, EventArgs e)
        {
            this.Visibility = System.Windows.Visibility.Visible;
            this.ShowInTaskbar = true;
            this.Activate();
        }

        private void Hide(object sender, EventArgs e)
        {
            this.ShowInTaskbar = false;
            this.Visibility = System.Windows.Visibility.Hidden;
        }

        private void Close(object sender, EventArgs e)
        {
            System.Environment.Exit(System.Environment.ExitCode); 
            //System.Windows.Application.Current.Shutdown();
        }

 private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
                e.Cancel = true;
                Hide();

        }

3.判断应用程序是否开启状态

//获取欲启动进程名
            string strProcessName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
            ////获取版本号
            //CommonData.VersionNumber = Application.ProductVersion;
            //检查进程是否已经启动,已经启动则显示报错信息退出程序。
            if (System.Diagnostics.Process.GetProcessesByName(strProcessName).Length > 1)
            {

                MessageBox.Show("MetadataSync running in background!", "Message", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                Application.Current.Shutdown();
                return;
            }

4.更新app.config的AppSettings

string key = "ScheduleLastUpload", value = DateTime.Now.ToString();
                    Configuration conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    bool hasSetKey = false;
                    foreach (string item in conf.AppSettings.Settings.AllKeys)
                    {
                        if (item == key)
                        {
                            conf.AppSettings.Settings[item].Value = value;

                            hasSetKey = true;
                        }
                    }
                    if (hasSetKey == false)
                    {
                        conf.AppSettings.Settings.Add(key, value);
                    }
                    ConfigurationManager.AppSettings.Set(key, value);
                    conf.Save();

5、给TextBlock加ToolTip,绑定自身

 <TextBlock ToolTip="{Binding RelativeSource={RelativeSource Self},Path=Text}"
Text="{Binding Path=Patientmain,
Converter={StaticResource fullNameConverter}}"
TextTrimming="CharacterEllipsis">
</TextBlock>
6.Margin与Padding

  Margin(外边距),指的是元素周围的距离,决定了元素周围留下的空白大小;Padding(内边距),指的是元素边界与其内容之间的距离。做过网页设计、用过CSS的同学对margin和padding属性肯定不陌生,但也有所区别。WPF中的Margin值可以为一个数字、一对数字和四个数字。

  一个数字代表四周距离相同,为指定值。一对数字时,第一个数字表示左侧和右侧距离相同,为指定值;第二个数字表示顶部和底部距离相同,为指定值。(与CSS中顺序不同)。四个数字,分别表示左侧、顶部、右侧、底部距离,该顺序与CSS不同。

  CSS中margin和padding属性顺序是:两个数字对应左右、上下;四个数字对应上、右、下、左;

区别HTML DOM margin属性

定义和用法

margin属性设置元素的外边距。

该属性可使用1到4个值:

如果规定一个值,比如div{margin:50px}-所有的外边距都是50px

如果规定两个值,比如div{margin:50px10px}-上下外边距是50px,左右外边距是10px。

如果规定三个值,比如div{margin:50px10px20px}-上外边距是50px,而左右外边距是10px,下外边距是20px。

如果规定四个值,比如div{margin:50px10px20px30px}-上外边距是50px,右外边距是10px,下外边距是20px,左外边距是30px。

计算:

继存INotifyPropertyChanged

public class NotificationObject : INotifyPropertyChanged
{

public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string proname)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(proname));
}
}

public class TestDemo1CalcuNumber : NotificationObject
{
private int _num1;
public int Num1
{
get { return _num1; }
set
{
_num1 = value;
RaisePropertyChanged("Num1");
}
}

}

然后在VIEWMODEL中可能定义绑定事件,先执行属性中的Set属性RaisePropertyChanged("Num1");,然后执行public void RaisePropertyChanged(string proname),然后执行CalcuNumber_PropertyChanged,最后执行属性中的get属性。

CalcuNumber.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(CalcuNumber_PropertyChanged);

void CalcuNumber_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "Num1" || e.PropertyName == "Num2")
{
CalcuNumber.Result = CalcuNumber.Num1 + CalcuNumber.Num2;
}
}

 

弹出屏外层灰色背景半透明背景

<Grid x:Name="GrdGraphicalResults" Grid.RowSpan="3" Visibility="Collapsed">
<Grid.Background>
<SolidColorBrush Color="Black" Opacity="0.6"></SolidColorBrush>
</Grid.Background>
<Border Background="White">

....

</Border>

</Grid>

 

style使用converter

<Style TargetType="{x:Type DataGridRow}" BasedOn="{StaticResource DataGridRowStyle}">

<Setter Property="Visibility" Value="{Binding IsDeleted,Converter={StaticResource BooleanToVisibilityInverseConverter}}" />
</Style>

 

RelativeSource绑定

在WPF绑定的时候,指定绑定源时,有一种办法是使用RelativeSource。

这种办法的意思是指当前元素和绑定源的位置关系。

第一种关系: Self

举一个最简单的例子:在一个StackPanel中,有一个TextBlock。

1
2
<TextBlock FontSize="18" FontWeight="Bold" Margin="10"
                 Background="Red" Width="80" Height="{Binding RelativeSource={RelativeSource Self},Path=Width}">MultiBinding Sample</TextBlock>

如果想让textbox的width和height相同,通过设置属性Height="{Binding RelativeSource={RelativeSource Self},Path=Width}" 就可以实现。

 

第二种关系:TemplatedParent

例如为一个Button写一个样式,修改Button为椭圆型。同时需要椭圆的背景色和Button的背景色相同。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Green"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid>
                            <Ellipse>
                                <Ellipse.Fill>
                                    <SolidColorBrush Color="{Binding Path=Background.Color,RelativeSource={RelativeSource TemplatedParent}}"/>
                                </Ellipse.Fill>
                            </Ellipse>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

 在这个例子中 TemplateParent就是指的Button

 

第三种关系:AncestorType

指定绑定源为某个父元素

复制代码
<Grid>

          <Label Background = {Binding Path=Background, RelativeSource={RelativeSource AncestorType={x:Type Grid}}}/>

     </Grid>
复制代码

这个例子中Label的背景色和Grid的背景色一样。

 

本事例是打开win8系统触摸键盘。

private void OpenKeyBoardHandler()
{
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = @"C:\Program Files\Common Files\microsoft shared\ink\TabTip.exe";
info.Arguments = "";
info.WindowStyle = ProcessWindowStyle.Hidden;
Process pro = Process.Start(info);
pro.WaitForExit();
this.Close();
}

7.mvvm send key

xaml:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
<textbox text="{Binding text,mode=TwoWay,UpdatesourceTrigger=Propertychanged}">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="KeyUp">
      <ei:CallMethodAction TargetObject="{Binding}" MethodName="SeachKeyUpCommand"/>
    </i:EventTrigger>
</i:Interaction.Triggers>
</textbox>
viewmodel:

public void SeachKeyUpCommand(object sender, System.Window.Input.KeyEventArgs e)
{
  if(e.Key.Equals(System.Window.Input.Key.Enter))
  {
    //TODO search
  }
}

8.ScrollViewer阻断内部滚动

private void SvrGroupDetail_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
try
{
var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
eventArg.RoutedEvent = MouseWheelEvent;
eventArg.Source = sender;
ScrollViewer scrollViewer = (ScrollViewer)sender;
scrollViewer.RaiseEvent(eventArg);
}
catch (Exception ex)
{
OneLog.E(ex);
ConfirmDialogState.ShowMessage(ex.Message);
}
}
}

9.监听

C# FileSystemWatcher 在监控文件夹和文件时的用法

https://blog.csdn.net/ab17171313/article/details/82423630